Difference between two date in seconds [duplicate] - javascript

I'm trying to get a difference between two dates in seconds. The logic would be like this :
set an initial date which would be now;
set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )
get the difference between those two ( the amount of seconds )
The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.
I've been trying something like this :
var _initial = new Date(),
_initial = _initial.setDate(_initial.getDate()),
_final = new Date(_initial);
_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);
var dif = Math.round((_final - _initial) / (1000 * 60));
The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)

The Code
var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.
The explanation
You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00
Rant
Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.
For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.
Useful docs for this answer
Why 1970?
Date object
Date's getTime method
Date's getDate method
Need more accuracy than just seconds?

You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);

Below code will give the time difference in second.
import Foundation
var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
alert(timeDiffInSecond );

<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();
var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>

Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);

time difference between now and 10 minutes later using momentjs
let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');
let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;

let startTime = new Date(timeStamp1);
let endTime = new Date(timeStamp2);
to get the difference between the dates in seconds ->
let timeDiffInSeconds = Math.floor((endTime - startTime) / 1000);
but this porduces results in utc(for some reason that i dont know).
So you have to take account for timezone offset, which you can do so by adding
new Date().getTimezoneOffset();
but this gives timezone offset in minutes, so you have to multiply it by 60 to get the difference in seconds.
let timeDiffInSecondsWithTZOffset = timeDiffInSeconds + (new Date().getTimezoneOffset() * 60);
This will produce result which is correct according to any timezone & wont add/subtract hours based on your timezone relative to utc.

Define two dates using new Date().
Calculate the time difference of two dates using date2. getTime() – date1. getTime();
Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)

const getTimeBetweenDates = (startDate, endDate) => {
const seconds = Math.floor((endDate - startDate) / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
return { seconds, minutes, hours, days };
};

try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:
var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds();
var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds();
alert(specifiedTimeSeconds-currentTimeSeconds);

Related

calculating time difference in iso time format in javascript?

I have two date string in ISO format. I am calculating the minutes difference between them using moment js.
var currenttime = new Date().toISOString();
var expiretime = '2020-06-05T12:18:33.000Z';
let minutes = moment(expiretime, 'YYYY-MM-DD[T]HH:mm:ss. SSS[Z]').diff(moment(currenttime, 'YYYY-MM-DD[T]HH:mm:ss. SSS[Z]'), 'minutes');
console.log(minutes)
Now i have two questions
Is this is the best way to calculate the minutes difference ?
When i run new Date().toISOString() the value before z is the supposed to be the timezone but on every restart it changes ?
Please let me know what is the issue ?
I don't think you have to include moment for this purpose only, this can be done in ordinary Javascript.
To calculate time difference just subtract the two timestamps which will give the difference in milliseconds. Then divide by 60*1000 which will give the time difference in minutes.
let currentTime = new Date();
let expireTime = new Date('2020-06-05T12:18:33.000Z');
let minutes = (expireTime - currentTime) / (1000 * 60);
console.log(minutes);
For your first question, what you can do is simply subtract the two dates (date objects and not strings) ,
Newer date - Older date ( this will give the result in milliseconds)
or use Math.abs() function to calculate milliseconds -
var msec = Math.abs( currenttime - expiretime );
and convert this to minutes using -
var min = Math.floor((msec/1000)/60);
2)
Z in the datetime string stands for Zulu, it indicates that the time is in UTC format.
You can simply subtract two date objects.
var currenttime = new Date();
var currenttime_UTC = currenttime.getUTCDate();
var expiretime = new Date('2020-06-05T12:18:33.000Z');
var msec = Math.abs( currenttime_UTC - expiretime );
var min = Math.floor((msec/1000)/60);

Calculate time remaining between now and a precise hour of next day

What's the most concise, performant way to get in Javascript the minutes remaining between now, and the upcoming day at 01:00 (am)?
Then, once the current time is after 01:00, I start calculating the difference to the next.
in javascript, a specified date can be provided like this
var date1 = new Date('June 6, 2019 03:24:00');
or it can be specified like this
var date2 = new Date('2019-6-6T03:24:00');
javascript can natively subtract 2 dates
console.log(date1 - date2);
//expected 0;
using this method will output the difference in the dates in milliseconds,
to get minutes you'll want to divide the value by 60000;
so
var futureTime = new Date('2019-06-06T07:24:00');
//there must be a 0 infront of 1 digit numbers or it is an invalid date
var now = new Date();
var difference = (futureTime - now) / 60000;
//get minutes by dividing by 60000
//doing Date() with no arguments returns the current date
read about the javascript Date object here for more information
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
let now = new Date();
let next1am = new Date();
next1am.setHours(1, 0, 0, 0); // same as now, but at 01:00:00.000
if (next1am < now) next1am.setDate(next1am.getDate() + 1); // bump date if past
let millisecondDiff = next1am - now;
let minuteDiff = Math.floor(millisecondDiff / 1000 / 60);
you can you moment.js here
var current = new Date()
var end = new Date(start.getTime() + 3600*60)// end time to calculate diff
var minDiff = end - start; // in millisec
You can calculate by pure JavaScript:
let today = new Date();
let [y,M,d,h,m,s] = '2019-06-04 05:00:11'.split(/[- :]/);
let yourDate = new Date(y,parseInt(M)-1,d,h,parseInt(m)+30,s);
let diffMs = (yourDate - today);
let diffDays = Math.floor(diffMs / 86400000); // days
let diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
let diffMins = (diffDays * 24 * 60)
+ (diffHrs *60)
+ Math.round(((diffMs % 86400000) % 3600000) / 60000); // The overall result
// in minutes
In, addition avoid using the built–in parser for any non–standard format, e.g. in Safari new Date("2019-04-22 05:00:11") returns an invalid date. You really shouldn't even use if for standardized formats as you will still get unexpected results for some formats. Why does Date.parse give incorrect results?

Subtracting days from a date in javascript

I have 2 <input type="text"> tags and I enter dates in them like this 22-05-2013
I want to subtract 22-06-2012 from that date
How do I do this?
I've tried this code but it didn't work:
function returnDate(nDays){
var now = new Date();
var dayOfTheWeek = now.getDay();
now.setTime(now.getTime() - nDays * 24 * 60 * 60 * 1000);
alert(now); // returns current date
alert(now.getFullYear() + "/"+(now.getMonth()+1)+"/"+now.getDate()) // returns new calculated date
}
So I need the difference between 22-05-2013 and 22-06-2012
The best way to do it would be to use Moment.js. It has fantastic support for dates.
In javascript you could subtract 2 Date objects and this will return the number of milliseconds between them. For example:
var date1 = new Date('2013-06-22 01:00:00');
var date2 = new Date('2013-06-22 01:00:01');
var result = date2 - date1;
alert(result); // shows 1000 which is 1 second
Simple:
new Date(mydate1 - mydate2).getDay() ;
This will give you the number of days.
I would suggest you use Date.js though, which would be even simpler.

How to calculate number of days between two dates

I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.
I should get result as 6 but I am getting 5.
function SetDays(invoker) {
var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();
var oneDay=1000 * 60 * 60 * 24;
var difference_ms = Math.abs(end.getTime() - start.getTime())
var diffValue = Math.round(difference_ms / oneDay);
}
Can anyone tell me how I can get exact difference?
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by #kotpal in the comments).
Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.
Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);
This works for me:
const from = '2019-01-01';
const to = '2019-01-08';
Math.abs(
moment(from, 'YYYY-MM-DD')
.startOf('day')
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
) + 1
);
I made a quick re-usable function in ES6 using Moment.js.
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {
const getDateAsArray = (date) => {
return moment(date.split(/\D+/), date_format);
}
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;
}
console.log(getDaysDiff('2019-10-01', '2019-10-30'));
console.log(getDaysDiff('2019/10/01', '2019/10/30'));
console.log(getDaysDiff('2019.10-01', '2019.10 30'));
console.log(getDaysDiff('2019 10 01', '2019 10 30'));
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));
console.log(getDaysDiff('10-01-2019', '10-30-2019'));
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
// today
const date = new Date();
// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();
// Difference in Days
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

How to round to nearest hour using JavaScript Date Object

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

Categories