Why Time difference gives me 2 different results - javascript

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);

Related

How to add hours to string formatted as HH:MM:SS in 24 hour format

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

Getting time difference between two times in javascript [duplicate]

This question already has answers here:
Check time difference in Javascript
(19 answers)
Closed 8 years ago.
I have tried to get the time difference between 2 different times and i am getting it correctly for hours and minutes. But if the second is greater than the first it will getting the problem. The time is displaying with negative data.
for example
Start time : 00:02:59
End time : 00:05:28
If i getting the difference between start and end time
00:05:28 - 00:02:59 = 00:3:-31
Which is not a correct value. I'm using the following script for getting this value.
var start_time = $("#startTime").val();
var end_time = $("#endTime").val();
var startHour = new Date("01/01/2007 " + start_time).getHours();
var endHour = new Date("01/01/2007 " + end_time).getHours();
var startMins = new Date("01/01/2007 " + start_time).getMinutes();
var endMins = new Date("01/01/2007 " + end_time).getMinutes();
var startSecs = new Date("01/01/2007 " + start_time).getSeconds();
var endSecs = new Date("01/01/2007 " + end_time).getSeconds();
var secDiff = endSecs - startSecs;
var minDiff = endMins - startMins;
var hrDiff = endHour - startHour;
alert(hrDiff+":"+minDiff+":"+secDiff);
anyone please tell me how to get the time difference between two times correctly even considering with seconds
Try doing this
var date1 = new Date(2000, 0, 1, 9, 0); // 9:00 AM
var date2 = new Date(2000, 0, 1, 17, 0); // 5:00 PM
if (date2 < date1) {
date2.setDate(date2.getDate() + 1);
}
var diff = date2 - date1;
// 28800000 milliseconds (8 hours)
You can then convert milliseconds to hour, minute and seconds like this:
var msec = diff;
var hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
var mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
var ss = Math.floor(msec / 1000);
msec -= ss * 1000;
// diff = 28800000 => hh = 8, mm = 0, ss = 0, msec = 0

String to date conversion not working correctly in Javascript

I need to get time difference in this format: "HH:MM:SS" using a Javascript.
I have tried this:
var diff = Date.parse( time2) - Date.parse( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
and this:
var diff = new Date( time2) - new Date( time1 );
var total_time = (diff / 1000 / 60 / 60) + ":" + (diff / 1000 / 60) + ":" + (diff / 1000);
These are the values of time2 and time1:
time1: "2012-11-07 15:20:32.161"
time2: "2012-11-07 17:55:41.451"
And result I am getting in both cases is:
total_time= 0.5250819444444444:31.504916666666666:1890.295
Which you can see is not correct
I think you are getting wrong diff value because of the millisecond part in the date delimited by .. Its not being accepted correctly by the data parser.
Try using the date and time part excluding the milliseconds as below:
var diff = Date.parse(time2.split(".")[0]) - Date.parse( time1.split(".")[0]);
Also while you are getting wrong difference diff, your time computation is also wrong.
It should be:
var second = Math.floor(diff /1000);
//convert the seconds into minutes and remainder is updated seconds value
var minute = Math.floor(second /60);
second = second % 60;
//convert the minutes into hours and remainder is updated minutes value
var hour = Math.floor(minute/60);
minute = minute %60;
var total_time= hour+":" minute+":"+second;
You forgot to remove the number of milliseconds you already calculated from diff. Here is a very verbose example on how you do it in a propper way.
var time1 = "2012-11-07 15:20:32.161",
time2 = "2012-11-07 17:55:41.451",
SECOND = 1000,
MINUTE = SECOND* 60,
HOUR = MINUTE* 60;
var diff = new Date(time2) - new Date(time1);
var hours = Math.floor(diff / HOUR); // Calculate how many times a full hour fits into diff
diff = diff - (hours * HOUR); // Remove hours from difference, we already caluclated those
var minutes = Math.floor(diff / MINUTE); // Calculate how many times a full minute fits into diff
diff = diff - (minutes * MINUTE); // Remove minutes from difference
var seconds = Math.floor(diff / SECOND); // As before
diff = diff - (seconds * SECOND);
var rest = diff;
var total_time = hours + ":" + minutes + ":" + seconds + " " + rest ;
DEMO

Calculate Time Difference with JavaScript

I have two HTML input boxes, that need to calculate the time difference in JavaScript onBlur (since I need it in real time) and insert the result to new input box.
Format example: 10:00 & 12:30 need to give me: 02:30
Thanks!
Here is one possible solution:
function diff(start, end) {
start = start.split(":");
end = end.split(":");
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);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes;
}
DEMO: http://jsfiddle.net/KQQqp/
Try This
var dif = ( new Date("1970-1-1 " + end-time) - new Date("1970-1-1 " + start-time) ) / 1000 / 60 / 60;
tl;dr
One off run
const t1 = new Date(1579876543210) // your initial time
const t2 = new Date(1579987654321) // your later time
const diff = t2-t1
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const humanDiff = `${Math.floor(diff/HRS)}:${Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})}:${Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})}.${Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})}`
console.log("humanDiff:", humanDiff)
// > humanDiff: 30:51:51.0111
As a function
function humanDiff (t1, t2) {
const diff = Math.max(t1,t2) - Math.min(t1,t2)
const SEC = 1000, MIN = 60 * SEC, HRS = 60 * MIN
const hrs = Math.floor(diff/HRS)
const min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
const sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
const ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
return `${hrs}:${min}:${sec}.${ms}`
}
const t1 = new Date(1579876543210)
const t2 = new Date(1579987654321)
console.log("humanDiff(t1, t2):", humanDiff(t1, t2))
// > humanDiff: 30:51:51.0111
Explanation
Adjust humanDiff for your maximum and minimum reportable increments and formatting needs:
const t1 = new Date(1579876543210) // Set your initial time (`t1`)
const t2 = new Date(1579986654321) // , conclusion time (`t2`), and
const diff = t2-t1 // calculate their difference in milliseconds
console.log(" t2:", t2.toISOString()) // > t2: 2020-01-25T21:27:34.321Z
console.log(" t1:", t1.toISOString()) // > t1: 2020-01-24T14:35:43.210Z
console.log(" diff:", diff) // > diff: 111111111
// Set your constant time values for easy readability
const SEC = 1000
const MIN = 60 * SEC
const HRS = 60 * MIN
/* For a given unit
1) disregard any previously relevant units, e.g. to calculate minutes, we can
disregard all hours & focus on only the remainder - `(diff%HRS)`
2) divide the remainder by the given unit, e.g. for minutes, `(diff%HRS)/MIN`
3) disregard any remainder, e.g. again for minutes, `Math.floor((diff%HRS)/MIN)`
NOTE: for your maximum unit (HRS in the examples below) you probably _don't_
want to disregard high values, e.g. If the difference is >24 hrs and something,
you should either include a DAYS value, or simply display 30 hrs */
let hrs = Math.floor(diff/HRS)
let min = Math.floor((diff%HRS)/MIN)
let sec = Math.floor((diff%MIN)/SEC)
let ms = Math.floor(diff % SEC) // just the remainder
// BUT ms IS NOT ACTUALLY CORRECT, see humanDiff_3 for the fix ;-)
let humanDiff_1 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_1:", humanDiff_1)
// > humanDiff_1: 30:51:51.111
sec = Math.round((diff%MIN)/SEC) // can also just round the last unit
const humanDiff_2 = `${hrs} hrs ${min} mins & ${sec} secs`
console.log("humanDiff_2:", humanDiff_2)
// > humanDiff_2: 30 hrs 51 mins & 51 secs
/* To ensure a set number of digits, format the numbers with `toLocaleString`'s
`minimumIntegerDigits`, if more than 3 digits, also use its `useGrouping` */
hrs = Math.floor(diff/HRS)
min = Math.floor((diff%HRS)/MIN).toLocaleString('en-US', {minimumIntegerDigits: 2})
sec = Math.floor((diff%MIN)/SEC).toLocaleString('en-US', {minimumIntegerDigits: 2})
ms = Math.floor(diff % SEC).toLocaleString('en-US', {minimumIntegerDigits: 4, useGrouping: false})
const humanDiff_3 = `${hrs}:${min}:${sec}.${ms}`
console.log("humanDiff_3:", humanDiff_3)
// > humanDiff_3: 30:51:51.0111
// NOTE: milliseconds are now 4 digits
This solution works for calculating diff between to separate military times
Example format: start = 23:00 / end = 02:30
function diff(start, end) {
start = start.split(":");
end = end.split(":");
if(Number(start[0]) > Number(end[0]) ) {
var num = Number(start[0])
var countTo = Number(end[0]);
var count = 0;
for (var i = 1; num != countTo;) {
num = num + i
if(num > 24) {
num = 0
}
count++
}
var hours = count - 1;
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
if(startDate.getMinutes() > endDate.getMinutes()) {
var hours = count - 2;
var diff = 60 - (startDate.getMinutes() - endDate.getMinutes());
} else {
var diff = endDate.getMinutes() - startDate.getMinutes();
}
var minutes = diff
} else {
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);
}
var returnValue = (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes
return returnValue;
}
Well this work almost great. Now use this code to calculate: 23:50 - 00:10 And see what you get.Or even 23:30 - 01:30. That's a mess.
Because getting the answer the other way in php is:
$date1 = strtotime($_POST['started']);
$date2 = strtotime($_POST['ended']);
$interval = $date2 - $date1;
$playedtime = $interval / 60;
But still, it works like yours.
I guess have to bring in the dates aswell?
And again: My hard research and development helped me.
if (isset($_POST['calculate'])) {
$d1 = $_POST['started'];
$d2 = $_POST['ended'];
if ($d2 < $d1) {
$date22 = date('Y-m-');
$date222 = date('d')-1;
$date2 = $date22."".$date222;
} else {
$date2 = date('Y-m-d');
}
$date1 = date('Y-m-d');
$start_time = strtotime($date2.' '.$d1);
$end_time = strtotime($date1.' '.$d2); // or use date('Y-m-d H:i:s') for current time
$playedtime = round(abs($start_time - $end_time) / 60,2);
}
And that's how you calculate time over to the next day.
//edit. First i had date1 jnd date2 switched. I need to -1 because this calculation only comes on next day and the first date vas yesterday.
After improving and a lot of brain power with my friend we came up to this:
$begin=mktime(substr($_GET["start"], 0,2),substr($_GET["start"], 2,2),0,1,2,2003);
$end=mktime(substr($_GET["end"], 0,2),substr($_GET["end"], 2,2),0,1,3,2003);
$outcome=($end-$begin)-date("Z");
$minutes=date("i",$outcome)+date("H",$outcome)*60; //Echo minutes only
$hours = date("H:i", $outcome); //Echo time in hours + minutes like 01:10 or something.
So you actually need only 4 lines of code to get your result. You can take only minutes or show full time (like difference is 02:32) 2 hours and 32 minutes.
What's most important: Still you can calculate overnight in 24 hour clock aka: Start time 11:50PM to let's say 01:00 AM (in 24 hour clock 23:50 - 01:00) because in 12 hour mode it works anyway.
What's most important: You don't have to format your input. You can use just plain 2300 as 23:00 input. This script will convert text field input to correct format by itself.
Last script uses standard html form with method="get" but you can convert it to use POST method as well.
This is an updated version of one that was already submitted. It is with the seconds.
function diff(start, end) {
start = start.split(":");
end = end.split(":");
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);
diff -= minutes * (1000 * 60);
var seconds = Math.floor(diff / 1000);
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes + (seconds<= 9 ? "0" : "") + seconds;
}
My Updated Version:
Allows for you to convert the dates into milliseconds and go off of that instead of splitting.
Example Does -- Years/Months/Weeks/Days/Hours/Minutes/Seconds
Example: https://jsfiddle.net/jff7ncyk/308/
With seconds you provided is not get result to me please find my updated function giving you the correct seconds here - By Dinesh J
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1],start[2], 0);
var endDate = new Date(0, 0, 0, end[0], end[1],end[2], 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);
var seconds = Math.floor(diff / 1000)-120;
// If using time pickers with 24 hours format, add the below line get exact hours
if (hours < 0)
hours = hours + 24;
return (hours <= 9 ? "0" : "") + hours + ":" + (minutes <= 9 ? "0" : "") + minutes+ ":" + (seconds <= 9 ? "0" : "") + seconds;
}
Depending on what you allow to enter, this one will work. There may be some boundary issues if you want to allow 1am to 1pm
NOTE: This is NOT using a date objects or moment.js
function pad(num) {
return ("0"+num).slice(-2);
}
function diffTime(start,end) {
var s = start.split(":"), sMin = +s[1] + s[0]*60,
e = end.split(":"), eMin = +e[1] + e[0]*60,
diff = eMin-sMin;
if (diff<0) { sMin-=12*60; diff = eMin-sMin }
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + ":" + pad(m);
}
document.getElementById('button').onclick=function() {
document.getElementById('delay').value=diffTime(
document.getElementById('timeOfCall').value,
document.getElementById('timeOfResponse').value
);
}
<input type="time" id="timeOfCall">
<input type="time" id="timeOfResponse">
<button type="button" id="button">CLICK</button>
<input type="time" id="delay">
calTimeDifference(){
this.start = dailyattendance.InTime.split(":");
this.end = dailyattendance.OutTime.split(":");
var time1 = ((parseInt(this.start[0]) * 60) + parseInt(this.start[1]))
var time2 = ((parseInt(this.end[0]) * 60) + parseInt(this.end[1]));
var time3 = ((time2 - time1) / 60);
var timeHr = parseInt(""+time3);
var timeMin = ((time2 - time1) % 60);
}
TimeCount = function()
{
t++;
var ms = t;
if (ms == 99)
{
s++;
t = 0;
if ( s == 60)
{
m++;
s = 0;
}
}
Dis_ms = checkTime(ms);
Dis_s = checkTime(s);
Dis_m = checkTime(m);
document.getElementById("time_val").innerHTML = Dis_m + ":" + Dis_s+ ":" + Dis_ms;
}
function checkTime(i)
{
if (i<10) {
i = "0" + i;
}
return i;
}
Try this: actually this a problem from codeeval.com
I solved it in this way .
This program takes a file as the argument so i used a little node js to read the file.
Here is my code.
var fs = require("fs");
fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) {
if (line !== "") {
var arr = line.split(" ");
var arr1 = arr[0].split(":");
var arr2 = arr[1].split(":");
var time1 = parseInt(arr1[0])*3600 + parseInt(arr1[1])*60 + parseInt(arr1[2]);
var time2 = parseInt(arr2[0])*3600 + parseInt(arr2[1])*60 + parseInt(arr2[2]);
var dif = Math.max(time1,time2) - Math.min(time1,time2);
var ans = [];
ans[0] = Math.floor(dif/3600);
if(ans[0]<10){ans[0] = "0"+ans[0]}
dif = dif%3600;
ans[1] = Math.floor(dif/60);
if(ans[1]<10){ans[1] = "0"+ans[1]}
ans[2] = dif%60;
if(ans[2]<10){ans[2] = "0"+ans[2]}
console.log(ans.join(":"));
}
});
We generally need time difference to estimate time taken by I/O operations, SP call etc, the simplest solution for NodeJs (the console is in callback- async execution) is following:
var startTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
callYourExpectedFunction(param1, param2, function(err, result){
var endTime = new Date().getTime();
//This will give you current time in milliseconds since 1970-01-01
console.log(endTime - startTime)
//This will give you time taken in milliseconds by your function
if(err){
}
else{
}
})

How to add hours to a Date object?

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).

Categories

Resources