Related
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?
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);
I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);
This should just work
EDIT: Fixed bug pointed by #bdukes
EDIT:
For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().
So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
JavaScript perfectly supports date difference out of the box
https://jsfiddle.net/b9chris/v5twbe3h/
var msMinute = 60*1000,
msDay = 60*60*24*1000,
a = new Date(2012, 2, 12, 23, 59, 59),
b = new Date("2013 march 12");
console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
Now some pitfalls. Try this:
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
So if you have risk of adding a number and Date, convert Date to number directly.
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
See JsFiddle DEMO
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
//Customise date2 for your required future time
showDiff();
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death.";
setTimeout(showDiff,1000);
}
for your HTML Code:
<div id="showTime"></div>
If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.
So to set your end date to 2 weeks after your start date, do something like this:
function GetEndDate(startDate)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate()+14);
return endDate;
}
To return the difference (in days) between two dates, do this:
function GetDateDiff(startDate, endDate)
{
return endDate.getDate() - startDate.getDate();
}
Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
Thanks #Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:
// don't update end date if there's already an end date but not an old start date
if (!oldEnd || oldBegin) {
var selectedDateSpan = 1800000; // 30 minutes
if (oldEnd) {
selectedDateSpan = oldEnd - oldBegin;
}
newEnd = new Date(newBegin.getTime() + selectedDateSpan));
}
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.
// This one returns a signed decimal. The sign indicates past or future.
this.getDateDiff = function(date1, date2) {
return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);
}
// This one always returns a positive decimal. (Suggested by Koen below)
this.getDateDiff = function(date1, date2) {
return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));
}
If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
Cheers,
Miguel
function compare()
{
var end_actual_time = $('#date3').val();
start_actual_time = new Date();
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time-start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
getTime(diffSeconds);
}
function getTime(seconds) {
var days = Math.floor(leftover / 86400);
//how many seconds are left
leftover = leftover - (days * 86400);
//how many full hours fits in the amount of leftover seconds
var hours = Math.floor(leftover / 3600);
//how many seconds are left
leftover = leftover - (hours * 3600);
//how many minutes fits in the amount of leftover seconds
var minutes = leftover / 60;
//how many seconds are left
//leftover = leftover - (minutes * 60);
alert(days + ':' + hours + ':' + minutes);
}
alternative modificitaion extended code..
http://jsfiddle.net/vvGPQ/48/
showDiff();
function showDiff(){
var date1 = new Date("2013/01/18 06:59:00");
var date2 = new Date();
//Customise date2 for your required future time
var diff = (date2 - date1)/1000;
var diff = Math.abs(Math.floor(diff));
var years = Math.floor(diff/(365*24*60*60));
var leftSec = diff - years * 365*24*60*60;
var month = Math.floor(leftSec/((365/12)*24*60*60));
var leftSec = leftSec - month * (365/12)*24*60*60;
var days = Math.floor(leftSec/(24*60*60));
var leftSec = leftSec - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + years + " years "+ month + " month " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds the life time has passed.";
setTimeout(showDiff,1000);
}
Below code will return the days left from today to futures date.
Dependencies: jQuery and MomentJs.
var getDaysLeft = function (date) {
var today = new Date();
var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));
var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
getDaysLeft('YYYY-MM-DD');
<html>
<head>
<script>
function dayDiff()
{
var start = document.getElementById("datepicker").value;
var end= document.getElementById("date_picker").value;
var oneDay = 24*60*60*1000;
var firstDate = new Date(start);
var secondDate = new Date(end);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
document.getElementById("leave").value =diffDays ;
}
</script>
</head>
<body>
<input type="text" name="datepicker"value=""/>
<input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
<input type="text" name="leave" value=""/>
</body>
</html>
this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message
take in mind there are three input elements the first txtFromQualifDate and second txtQualifDate and third txtStudyYears
it will show result of number of years with fraction
function getStudyYears()
{
if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')
{
var d1 = document.getElementById('txtFromQualifDate').value;
var d2 = document.getElementById('txtQualifDate').value;
var one_day=1000*60*60*24;
var x = d1.split("/");
var y = d2.split("/");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var dDays = (date2.getTime()-date1.getTime())/one_day;
if(dDays < 365)
{
alert("the date between start study and graduate must not be less than a year !");
document.getElementById('txtQualifDate').value = "";
document.getElementById('txtStudyYears').value = "";
return ;
}
var dMonths = Math.ceil(dDays / 30);
var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;
document.getElementById('txtStudyYears').value = dYears;
}
}
If you use Date objects and then use the getTime() function for both dates it will give you their respective times since Jan 1, 1970 in a number value. You can then get the difference between these numbers.
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
var getDaysLeft = function (date1, date2) {
var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));
var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
var date1='2018-05-18';
var date2='2018-05-25';
var dateDiff = getDaysLeft(date1, date2);
console.log(dateDiff);
To get the date difference in milliseconds between two dates:
var diff = Math.abs(date1 - date2);
I'm not sure what you mean by converting the difference back into a date though.
Many answers here are based on a direct subtraction of Date objects like new Date(…) - new Date(…). This is syntactically wrong. Browsers still accept it because of backward compatibility. But modern JS linters will throw at you.
The right way to calculate date differences in milliseconds is new Date(…).getTime() - new Date(…).getTime():
// Time difference between two dates
let diffInMillis = new Date(…).getTime() - new Date(…).getTime()
If you want to calculate the time difference to now, you can just remove the argument from the first Date:
// Time difference between now and some date
let diffInMillis = new Date().getTime() - new Date(…).getTime()
function checkdate() {
var indate = new Date()
indate.setDate(dat)
indate.setMonth(mon - 1)
indate.setFullYear(year)
var one_day = 1000 * 60 * 60 * 24
var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))
var str = diff + " days are remaining.."
document.getElementById('print').innerHTML = str.fontcolor('blue')
}
THIS IS WHAT I DID ON MY SYSTEM.
var startTime=("08:00:00").split(":");
var endTime=("16:00:00").split(":");
var HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));
console.log(HoursInMinutes/60);
I am trying to get the current time difference in hours and minutes between now and 12pm (midday). If it is past 12pm on the current day it must then count down the hours onto the next day.
I have looked around here for a while now and have found many examples on getting date differences but and am unable to get a working solution for time so have been playing around with writing my own. However I am unable to getTime(); to get hours and minutes from the millisecond timestamp on my new dates and am unsure why exactly. Here is my code:
dateone = new Date();
datetwo = new Date();
datetwo = datetwo.setHours(12);
dateone = dateone.getTime();
datetwo = datetwo.getTime();
if(dateone > datetwo) {
var seconds = dateone - datetwo;
} else {
var seconds = datetwo - dateone;
}
var d = seconds;
var minutes=(d/(1000*60))%60;
var hours=(d/(1000*60*60))%24;
var minutesround=Math.floor(minutes);
var hoursround=Math.round(hours);
var endtime = 12;
alert(hours);
alert(minutes);
If anyone is able to spot a better way of doing this, or can suggest anything it would be greatly appreciated!
Thanks,
Simon
Try
var d = new Date(), midDay = new Date();
midDay.setHours(12);
midDay.setMinutes(0);
midDay.setSeconds(0);
if(d > midDay) {
midDay.setDate(midDay.getDate() + 1)
}
var diff = (midDay.getTime() - d.getTime()) / 1000;
var hrs = parseInt(diff / 3600);
diff = diff % 3600;
var minutes = parseInt(diff / 60);
console.log(hrs, minutes)
Demo: Fiddle
I realize that the current timestamp can be generated with the following...
var timestamp = Math.round((new Date()).getTime() / 1000);
What I'd like is the timestamp at the beginning of the current day. For example the current timestamp is roughly 1314297250, what I'd like to be able to generate is 1314230400 which is the beginning of today August 25th 2011.
Thanks for your help.
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;
Well, the cleanest and fastest way to do this is with:
long timestamp = 1314297250;
long beginOfDay = timestamp - (timestamp % 86400);
where 86400 is the number of seconds in one day
var now = new Date; // now
now.setHours(0); // set hours to 0
now.setMinutes(0); // set minutes to 0
now.setSeconds(0); // set seconds to 0
var startOfDay = Math.floor(now / 1000); // divide by 1000, truncate milliseconds
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
var t = d / 1000;
Alternatively you could subtract the modulo of a days length in miliseconds e.g.
var day = 24*60*60*1000;
var start_of_today = Date.now() - Date.now() % day;
Luis Fontes' solution returns UTC time so it can be 1 hour (daylight saving time) different from setHours solution.
var d = new Date();
var t = d - (d % 86400000);
Simplified version of examples above (local time).
var d = new Date();
d.setHours(0,0,0,0);
var t = d / 1000;
Here you can find some performance tests: http://jsperf.com/calc-start-of-day
Another alternative for getting the beginning of the day is the following:
var now = new Date();
var beginningOfDay = new Date(now.getTime() -
now.getHours() * 60 * 60 * 1000 -
now.getMinutes() * 60 * 1000 -
now.getSeconds() * 1000 -
now.getMilliseconds());
var yoursystemday = new Date(new Date().getTime()-(120000*60+new Date().getTimezoneOffset()*60000));
yoursystemday = new Date();
var current_time_stamp = Math.round(yoursystemday.getTime()/1000);
For any date it's easy to get Timestamps of start/end of the date using ISO String of the date ('yyyy-mm-dd'):
var dateString = '2017-07-13';
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
To get ISO String of today you would use (new Date()).toISOString().substring(0, 10)
So to get TS for today:
var dateString = (new Date()).toISOString().substring(0, 10);
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay.getTime() / 1000;