It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).
Related
I am working on a project that requires a time in the future to be set using the Date object.
For example:
futureTime = new Date();
futureTime.setHours(futureTime.getHours()+2);
My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?
For example:
Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00
Any help would be appreciated!
Round the minutes and then clear the minutes:
var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00
function roundMinutes(date) {
date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}
The other answers ignore seconds and milliseconds components of the date.
The accepted answer has been updated to handle milliseconds, but it still does not handle daylight savings time properly.
I would do something like this:
function roundToHour(date) {
p = 60 * 60 * 1000; // milliseconds in an hour
return new Date(Math.round(date.getTime() / p ) * p);
}
var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00
date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00
A slightly simpler way :
var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);
Another solution, which is no where near as graceful as IAbstractDownvoteFactory's
var d = new Date();
if(d.getMinutes() >= 30) {
d.setHours(d.getHours() + 1);
}
d.setMinutes(0);
Or you could mix the two for optimal size.
http://jsfiddle.net/HkEZ7/
function roundMinutes(date) {
return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}
As a matter of fact Javascript does this default which gives wrong time.
let dateutc="2022-02-17T07:20:00.000Z";
let bd = new Date(dateutc);
console.log(bd.getHours()); // gives me 8!!!!!
it is even wrong for my local time because I am GMT+2 so it should say 9.
moment.js also does it wrong so you need to be VERY carefull
Pass any cycle you want in milliseconds to get next cycle example 1 hours
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(1 * 60 * 60 * 1000)); // 1 hours in milliseconds
I'm trying to add hours to time in the format of 24 hours say '23:59:59'. I need to add, for example, 2.5 hours so the time should roll to the next day and be shown as '02:30:00'.
What I have tried so far works until it reaches '23:59:59'. I need to show the next day time if it exceeds '23:59:59'. Here is what I have tried so far:
var time = $('#starttime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var time2 = $('#endtime').val().split(':');
var endtimeval = new Date();
endtimeval.setHours(+time2[0]);
endtimeval.setMinutes(time2[1]);
endtimeval.setSeconds(time2[2]);
var str = d.getHours() + parseInt($('#noofhours').val()) + ":" + time2[1] + ":" + time2[2];
$('#endtime').val(str);
Using a Date Object here is possibly unnecessary, modulo arithmetic should suffice.
const pad = n => {
const s = String(n);
return s.length > 1 ? s : '0' + s;
};
const addHours = (timeVal, numHours) => {
const [hr, min, sec] = timeVal.split(':').map(Number);
const [,lefty, righty] = String(numHours).match(/(\d+)(?:(\.\d+))?/).map(Number);
const hours = (hr + lefty) % 24;
const minutes = righty === undefined ?
min :
((righty * 60 | 0) + min) % 60;
return [hours, minutes, sec].map(pad).join(':');
};
addHours('23:59:59', 2.5) // "01:29:59"
Note that since there's no dates involved it will not accurately handle e.g. daylight savings time. Also note that minutes are in this example rounded down, you could repeat the logic for seconds if desired.
Note that your approach using Date objects will give different answers for the same inputs depending on when/where the logic runs, for the same reasons.
Make a custom date adder?
const add = (time, hours) => {
let [hh, mm, ss] = time.split(':');
const seconds = hours * 60 * 60;
ss = ss * 1 + seconds;
if (ss >= 60) {
mm = mm * 1 + ss / 60;
ss = (ss % 60).toPrecision(2).padStart(2, '0');
}
if (mm >= 60) {
hh = hh * 1 + mm / 60;
mm = (mm % 60).toPrecision(2).padStart(2, '0');
}
hh = (Math.floor(hh) % 24).toString().padStart(2, '0');
return hh + ':' + mm + ':' + ss;
}
console.log(add("23:59:59", 2.5));
you may apply DRY principle and refactor the code yourself. But it will get the job done according to your requirement.
The simple trick that I did is just converted the hours entered as float/int to a minute value by multiplying to 60 and created a date, with this just added the time I already have.
Here the solution with minimal steps:
var time = $('#endtime').val().split(':');
var d = new Date();
d.setHours(+time[0]);
d.setMinutes(time[1]);
d.setSeconds(time[2]);
var addeddate = new Date();
addeddate.setMinutes(parseFloat($('#noofhours').val()) * 60);
$('#endtime').val(("0" + (addeddate.getHours())).slice(-2) + ":" + ("0" + (addeddate.getMinutes())).slice(-2) + ":" + ("0" + (addeddate.getSeconds())).slice(-2)); //The answer that I needed in endtime id value.
You can use vanilla JavaScript Date methods fairly easily here. Most of the work is parsing the time string inputs and then concatenating the time string output. For example:
const start = '23:59:59';
const add = '2.5';
const [hh, mm, ss] = start.split(':').map(x => parseInt(x));
const d = new Date(new Date().setHours(hh, mm + (add * 60), ss));
const end = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(end);
// 2:29:59
I have this javascript code which should show the time. It works. I wan't to be able to add extra time though. Lets say that I want to add 1 hour.
<script type="text/javascript">
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
// This function gets the current time and injects it into the DOM
function updateClock() {
// Gets the current time
var now = new Date();
// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// Format hours, minutes and seconds
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');
// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds;
}
function start(){
setInterval('updateClock()', 200);
}
</script>
The first function calculates the milisecons that I want to add, and the second function is the "live clock". How do I implement the first function into the second one, so I get the working result?
for adding hours, use setHours :
// Gets the current time
var now = new Date();
console.log("actual time:", now);
now.setHours(now.getHours() + 1)
console.log("actual time + 1 hour:", now);
For references: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
Check out this fiddle.
The constructor Date(milliseconds) of class Date can be used here.
Here is the snippet.
var now = new Date();
alert(now);
var milliseconds = new Date().getTime() + (1 * 60 * 60 * 1000);
var later = new Date(milliseconds);
alert(later);
Check out this
fiddle here
var todayDate = new Date();
alert("After adding ONE hour : "+new Date(todayDate.setHours(todayDate.getHours()+1)) );
javascript date API is near to be completed, the existing methods of it can be use to add another functionality for this API, some says it is tedious but its not.
in order to add a method in a date we will access the prototype of this API,
like this.
Date.prototype.addTime = function(str){
function parse(str){
let arr = (typeof str == 'number')?[str]:str.split(":").map(t=>t.trim());
arr[0] = arr[0] || 0;
arr[1] = arr[1] || 0;
arr[2] = arr[2] || 0;
return arr
}
function arrToMill(arr){
let [h,m,s] = arr;
return (h*60*60*1000) + (m*60*1000) + (s*1000);
}
let date = new Date(this.getTime());
let parsed = parse(str);
date.setTime(date.getTime() + arrToMill(parsed));
return date;
}
getting it rockin.
this function is immutable
let date = new Date();
date.addTime(1);
date.addTime("01:00");`
How do I get the time difference of two values of 24hr format?
For example
var time1 = 22:30:00,
time2 = 06:30:00;
Difference should come as 08:00:00
You are much better off to do this type of maths with full date objects, otherwise you have to make guesses about the time values such as if the finish is less that the start, it must be on the next day.
The following includes a couple of helper functions and a main function to get the difference.
// Convert h:m:s to seconds
function hmsToSecs(s) {
var b = s.split(':');
return b[0]*3.6e3 + b[1]*60 + +b[2];
}
// Convert seconds to hh:mm:ss
function secsToHMS(n) {
function z(n){return (n<10? '0':'') + n;}
var sign = n < 0? '-' : '';
n = Math.abs(n);
return sign + z(n/3.6e3|0) + ':' + z(n%3.6e3/60|0) + ':' + z(n%60);
}
// Calculate time difference between two times
// start and finish in hh:mm:ss
// If finish is less than start, assume it's the following day
function timeDiff(start, finish) {
var s = hmsToSecs(start);
var f = hmsToSecs(finish);
// If finish is less than start, assume is next day
// so add 24hr worth of seconds
if (f < s) f += 8.64e4;
return secsToHMS(f - s);
}
console.log(timeDiff('22:30:00','06:30:00')); // 08:00:00
console.log(timeDiff('06:30:00','22:30:00')); // 16:00:00
Using full date objects, you can do:
var start = new Date(2014,5,5,22,30); // 22:30:00 on 5 June 2014
var finish = new Date(2014,5,6,6,30); // 06:30:00 on 6 June 2014
// Subtract dates to get difference in ms, convert to seconds and format
console.log(secsToHMS((finish - start)/1000)); // 08:00:00
console.log(secsToHMS((start - finish)/1000)); // -08:00:00
I Suggest that you should use jquery date.js library and then you can use its Timespan class like below:
var future = Date.parseExact("22:30:00", "hh:mm:ss");
var past = Date.parseExact("06:30:00", "hh:mm:ss");
var span = new TimeSpan(future - now);
and your difference in hours is as below:
span.getHours() + ":" span.getMinutes() + ":" span.getSeconds()
If you want Diff function in C#;
DateTime oldDate= "06/01/2014 12:00:00 AM";
TimeSpan timeDiff = DateTime.Now - oldDate;
int diff =Convert.ToInt32(timeDiff.TotalHours);
if you want it in JavaScript thats a script block should help you;
function diffDateTime(startDT, endDT) {
if (typeof startDT == 'string' && startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)) {
startDT = startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
startDT = startDT.toString().split(':');
var obstartDT = new Date();
obstartDT.setHours(startDT[0]);
obstartDT.setMinutes(startDT[1]);
obstartDT.setSeconds(startDT[2]);
}
else if (typeof startDT == 'string' && startDT.match(/^now$/i)) var obstartDT = new Date();
else if (typeof startDT == 'string' && startDT.match(/^tomorrow$/i)) {
var obstartDT = new Date();
obstartDT.setHours(24);
obstartDT.setMinutes(0);
obstartDT.setSeconds(1);
}
else var obstartDT = new Date(startDT);
if (typeof endDT == 'string' && endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)) {
endDT = endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
endDT = endDT.toString().split(':');
var obendDT = new Date();
obendDT.setHours(endDT[0]);
obendDT.setMinutes(endDT[1]);
obendDT.setSeconds(endDT[2]);
}
else if (typeof endDT == 'string' && endDT.match(/^now$/i)) var obendDT = new Date();
else if (typeof endDT == 'string' && endDT.match(/^tomorrow$/i)) {
var obendDT = new Date();
obendDT.setHours(24);
obendDT.setMinutes(0);
obendDT.setSeconds(1);
}
else var obendDT = new Date(endDT);
var secondsDiff = (obendDT.getTime() - obstartDT.getTime()) > 0 ? (obendDT.getTime() - obstartDT.getTime()) / 1000 : (86400000 + obendDT.getTime() - obstartDT.getTime()) / 1000;
secondsDiff = Math.abs(Math.floor(secondsDiff));
var oDiff = {}; // object that will store data returned by this function
oDiff.days = Math.floor(secondsDiff / 86400);
oDiff.totalhours = Math.floor(secondsDiff / 3600); // total number of hours in difference
oDiff.totalmin = Math.floor(secondsDiff / 60); // total number of minutes in difference
oDiff.totalsec = secondsDiff; // total number of seconds in difference
secondsDiff -= oDiff.days * 86400;
oDiff.hours = Math.floor(secondsDiff / 3600); // number of hours after days
secondsDiff -= oDiff.hours * 3600;
oDiff.minutes = Math.floor(secondsDiff / 60); // number of minutes after hours
secondsDiff -= oDiff.minutes * 60;
oDiff.seconds = Math.floor(secondsDiff); // number of seconds after minutes
return oDiff;
}
usage;
var objDiff = diffDateTime('06/01/2014 12:00:00 AM', 'now');
var dtdiff = objDiff.days + ' days, ' + objDiff.hours + ' hours, ' + objDiff.minutes + ' minutes, ' + objDiff.seconds + ' seconds';
Important: You have to remember that DateTime format must be in en-US format dd/MM/yyyy hh:mm:ss.
this code should give 0:40 minutes, however in one way gives me 0:20 minutes, and in the other way gives me 1:40 minutes.
var t1 = '12:05'.split(':'),
t2 = '12:45'.split(':');
var d1 = new Date(0,0,0,t1[0],t1[1]),
d2 = new Date(0,0,0,t2[0],t2[1]);
document.write(d1+'<BR>');
document.write(d2+'<BR>');
var d = new Date(d1-d2);
// should give 0:40 minutes
document.write(d.getHours() + ":" + d.getMinutes() + '<BR>');
// 0:20 minutes
var d = new Date(d2-d1);
document.write(d.getHours() + ":" + d.getMinutes() + '<BR>');
// 1:40 minutes
Any ideas?
You can write your own function to calculate two dates difference and show the result in HH:MM format.
Because Javascript returns two date difference in timestamp & if we use that timestamp to get JS date object it creates totally new date.
Here is the sample dateDiff function :
function dateDiff(){
var start = '12:05'.split(':'), // hardcoded value for sample
end = '12:45'.split(':'); // you can pass start and end value as parameter to dateDiff function.
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
return ( (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes);
}
Subtracting two dates gives you the number of milliseconds between them. Passing this to new Date gives you a new date object that many milliseconds from epoch.
If you want the number of minutes between two dates, just do this:
(d1-d2)/(60*1000);