How would you go about determining how many minutes until midnight of the current day using javascript?
function minutesUntilMidnight() {
var midnight = new Date();
midnight.setHours( 24 );
midnight.setMinutes( 0 );
midnight.setSeconds( 0 );
midnight.setMilliseconds( 0 );
return ( midnight.getTime() - new Date().getTime() ) / 1000 / 60;
}
Perhaps:
function minsToMidnight() {
var now = new Date();
var then = new Date(now);
then.setHours(24, 0, 0, 0);
return (then - now) / 6e4;
}
console.log(minsToMidnight());
or
function minsToMidnight() {
var msd = 8.64e7;
var now = new Date();
return (msd - (now - now.getTimezoneOffset() * 6e4) % msd) / 6e4;
}
console.log(minsToMidnight())
and there is:
function minsToMidnight(){
var d = new Date();
return (-d + d.setHours(24,0,0,0))/6e4;
}
console.log(minsToMidnight());
or even a one-liner:
minsToMidnight = () => (-(d = new Date()) + d.setHours(24,0,0,0))/6e4;
console.log(minsToMidnight());
You can get the current timestamp, set the hours to 24,
and subtract the old timestamp from the new one.
function beforeMidnight(){
var mid= new Date(),
ts= mid.getTime();
mid.setHours(24, 0, 0, 0);
return Math.floor((mid - ts)/60000);
}
alert(beforeMidnight()+ ' minutes until midnight')
Here's a one-liner to get milliseconds until midnight
new Date().setHours(24,0,0,0) - Date.now()
And for the minutes until midnight, we divide that by 60 and then by 1000
(new Date().setHours(24,0,0,0) - Date.now()) / 60 / 1000
Posting this as an alternative solution which works for any hour of the day.
const timeUntilHour = (hour) => {
if (hour < 0 || hour > 24) throw new Error("Invalid hour format!");
const now = new Date();
const target = new Date(now);
if (now.getHours() >= hour)
target.setDate(now.getDate() + 1);
target.setHours(hour);
target.setMinutes(0);
target.setSeconds(0);
target.setMilliseconds(0);
return target.getTime() - now.getTime();
}
const millisecondsUntilMidnight = timeUntilHour(24);
const minutesUntilMidnight = millisecondsUntilMidnight / (60 * 1000);
Related
I have created one timer application in javascript.
Firstly it takes the current UTC date to init timer with some reference. here's the code
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
var current_date = this.get_current_UTCDate();
this.project_timesheet_db.set_current_timer_activity({date: current_date});
this.start_interval();
this.initialize_timer();
this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");
Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.
This function is
start_interval: function() {
var timer_activity = this.project_timesheet_db.get_current_timer_activity();
var self = this;
this.intervalTimer = setInterval(function(){
self.$el.find(".pt_duration").each(function() {
var el_hour = $(this).find("span.hours");
var el_minute = $(this).find("span.minutes");
var minute = parseInt(el_minute.text());
if(minute >= 60) {
el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
minute = 0;
}
el_minute.text(_.str.sprintf("%02d", minute));
var el_second = $(this).find("span.seconds");
var seconds = parseInt(el_second.text()) + 1;
if(seconds > 60) {
el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
seconds = 0;
}
el_second.text(_.str.sprintf("%02d", seconds));
});
}, 1000);
},
Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.
thanks in advance for help
To convert H:M:S to seconds, you can use a simple function like:
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
Then to convert seconds back to HMS:
// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
var a = '01:43:28';
var b = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18
You may want to abbreviate the function names to say:
toHMS(toSec(a) - toSec(b)); // -10:39:18
Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.
Edit
The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.
If you have Date objects, you can get the difference between them in milliseconds using:
var diffMilliseconds = date0 - date1;
and convert to seconds:
var diffSeconds = diffMilliseconds / 1000;
and present as HH:MM:SS using the secondsToHMS function above:
secondsToHMS((date0 - date1) / 1000);
e.g.
var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);
console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18
I think there is a simpler solution.
function dateDiffToString(a, b){
// make checks to make sure a and b are not null
// and that they are date | integers types
diff = Math.abs(a - b);
ms = diff % 1000;
diff = (diff - ms) / 1000
ss = diff % 60;
diff = (diff - ss) / 60
mm = diff % 60;
diff = (diff - mm) / 60
hh = diff % 24;
days = (diff - hh) / 24
return days + ":" + hh+":"+mm+":"+ss+"."+ms;
}
var today = new Date()
var yest = new Date()
yest = yest.setDate(today.getDate()-1)
console.log(dateDiffToString(yest, today))
const dateDiffToString = (a, b) => {
let diff = Math.abs(a - b);
let ms = diff % 1000;
diff = (diff - ms) / 1000;
let s = diff % 60;
diff = (diff - s) / 60;
let m = diff % 60;
diff = (diff - m) / 60;
let h = diff;
let ss = s <= 9 && s >= 0 ? `0${s}` : s;
let mm = m <= 9 && m >= 0 ? `0${m}` : m;
let hh = h <= 9 && h >= 0 ? `0${h}` : h;
return hh + ':' + mm + ':' + ss;
};
This may be the simple answer
var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
More intuitive and easier to read.
function hmsToSeconds(t) {
const [hours, minutes, seconds] = t.split(':')
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
}
function secondsToHMS(secs) {
return new Date(secs * 1000).toISOString().substr(11, 8)
}
var startTime = '01:43:28';
var endTime = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18
I need to be able to round time to the next nearest 5 minutes.
Time now 11:54 - clock is 11:55
Time now 11:56 - clock is 12:00
It can never round down just always up to the next time.
I am using this code at the moment but this will round down as well
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(Math.round(date.getTime() / time) * time);
Add 2.5 minutes to your time, then round.
11:54 + 2.5 = 11:56:30 -> 11:55
11:56 + 2.5 = 11:58:30 -> 12:00
You could divide out 5, do a Math.ceil then multiply back up by 5
minutes = (5 * Math.ceil(minutes / 5));
I had the same problem, but I needed to round down, and I changed your code to this:
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() - (date.getTime() % time));
I think that to round up It wiil be something like this:
var time = 1000 * 60 * 5;
var date = new Date();
var rounded = new Date(date.getTime() + time - (date.getTime() % time));
Pass any cycle you want in milliseconds to get next cycle example 5,10,15,30,60 minutes
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(5 * 60 * 1000)); // pass in milliseconds
var b = Date.now() + 15E4,
c = b % 3E5;
rounded = new Date(15E4>=c?b-c:b+3E5-c);
With ES6 and partial functions it can be elegant:
const roundDownTo = roundTo => x => Math.floor(x / roundTo) * roundTo;
const roundUpTo = roundTo => x => Math.ceil(x / roundTo) * roundTo;
const roundUpTo5Minutes = roundUpTo(1000 * 60 * 5);
const ms = roundUpTo5Minutes(new Date())
console.log(new Date(ms)); // Wed Jun 05 2019 15:55:00 GMT+0200
I have code for get time difference form two time
var starthours = document.getElementById("time3").value;
var endhours = document.getElementById("time4").value;
start = starthours.split(".");
end = endhours.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);
document.getElementById("hourdiff").value = (hours < 9 ? "0" : "") + hours + "." + (minutes < 9 ? "0" : "") + minutes;
But now I have to add another time field for this results, I get that value using this code
var timetv = document.getElementById("timetv").value;
And I want to add this to above time difference how to do that, Please help me..
Start time = 10.30
End time = 12.30
Time TV = 01.15
Resualt = (End Time - Start time) + Time TV
And answer should be = 3.15
Try This,
var starthours = document.getElementById("time3").value;
var endhours = document.getElementById("time4").value;
var timetv = document.getElementById("timetv").value;
start = starthours.split(".");
end = endhours.split(".");
tvtime = timetv.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);
hours = hours + parseInt(tvtime[0]);
minutes = minutes + parseInt(tvtime[1]);
this one is for getting the value when you already have the dates parsed into Date object from your form.
http://jsfiddle.net/gLReS/
var time1 = new Date('2013/08/12 10:30');
var time2 = new Date('2013/08/12 12:30');
var time3 = new Date('2013/08/12 1:15');
var result = (time2.getTime() - time1.getTime()) + time3.getTime();
var resultTime = new Date(result);
alert(resultTime);
The other thing is however getting these objects, and this one depends on your date format.
I don't understand, what is your problem.
var d = new Date(
new Date(0, 0, 0, 12, 30) -
new Date(0, 0, 0, 10, 30) +
(+new Date(0, 0, 0, 1, 15)) // transform Date into timestamp
);
[d.getHours(), d.getMinutes()]; // [3, 15]
Also, I usually replace
(hours < 9 ? "0" : "") + hours
with
("0" + hours).slice(-2)
Is there a way to check if a date is less than 1 hour ago like this?
// old date
var olddate = new Date("February 9, 2012, 12:15");
// current date
var currentdate = new Date();
if (olddate >= currentdate - 1 hour) {
alert("newer than 1 hour");
else {
alert("older than 1 hour");
}
Also, different question - is there a way to add hours to a date like this?
var olddate = new Date("February 9, 2012, 12:15") + 15 HOURS; // output: February 10, 2012, 3:15
Define
var ONE_HOUR = 60 * 60 * 1000; /* ms */
then you can do
((new Date) - myDate) < ONE_HOUR
To get one hour from a date, try
new Date(myDate.getTime() + ONE_HOUR)
Using some ES6 syntax:
const lessThanOneHourAgo = (date) => {
const HOUR = 1000 * 60 * 60;
const anHourAgo = Date.now() - HOUR;
return date > anHourAgo;
}
Using the Moment library:
const lessThanOneHourAgo = (date) => {
return moment(date).isAfter(moment().subtract(1, 'hours'));
}
Shorthand syntax with Moment:
const lessThanOneHourAgo = (date) => moment(date).isAfter(moment().subtract(1, 'hours'));
the moment library can really help express this. The trick is to take the date, add time, and see if it's before or after now:
lastSeenAgoLabel: function() {
var d = this.lastLogin();
if (! moment(d).isValid()) return 'danger'; // danger if not a date.
if (moment(d).add(10, 'minutes').isBefore(/*now*/)) return 'danger'; // danger if older than 10 mins
if (moment(d).add(5, 'minutes').isBefore(/*now*/)) return 'warning'; // warning if older than 5mins
return 'success'; // Looks good!
},
Using moment will be much easier in this case, You could try this:
let hours = moment().diff(moment(yourDateString), 'hours');
It will give you integer value like 1,2,5,0etc so you can easily use condition check like:
if(hours < 1) {
Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result use this syntax:
let hours = moment().diff(moment(yourDateString), 'hours', true);
Let me know if you have any further query
//for adding hours to a date
Date.prototype.addHours= function(hrs){
this.setHours(this.getHours()+hrs);
return this;
}
Call function like this:
//test alert(new Date().addHours(4));
You can do it as follows:
First find difference of two dates i-e in milliseconds
Convert milliseconds into minutes
If minutes are less than 60, then it means date is within hour else not within hour.
var date = new Date("2020-07-12 11:30:10");
var now = new Date();
var diffInMS = now - date;
var msInHour = Math.floor(diffInMS/1000/60);
if (msInHour < 60) {
console.log('Within hour');
} else {
console.log('Not within the hour');
}
Plain JavaScript solution with in 12 days and 12 days ago option
const timeAgo = ( inputDate ) => {
const date = ( inputDate instanceof Date) ? inputDate : new Date(inputDate);
const FORMATTER = new Intl.RelativeTimeFormat('en');
const RANGES = {
years : 3600 * 24 * 365,
months : 3600 * 24 * 30,
weeks : 3600 * 24 * 7,
days : 3600 * 24,
hours : 3600,
minutes : 60,
seconds : 1
};
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
for (let key in RANGES) {
if ( RANGES[key] < Math.abs(secondsElapsed) ) {
const delta = secondsElapsed / RANGES[key];
return FORMATTER.format(Math.round(delta), key);
}
}
}
// OUTPUTS
console.log( timeAgo('2040-12-24') )
console.log( timeAgo('6 Sept, 2012') );
console.log( timeAgo('2022-05-27T17:45:01+0000') );
let d = new Date()
console.log( "Date will change: ", timeAgo( d.setHours(24,0,0,0) ) );
// d.setDate( d.getDate() - 0 );
d.setHours(-24,0,0,0); // (H,M,S,MS) | 24 hours format
console.log("Day started: " , timeAgo( d ) );
//try this:
// to compare two date's:
<Script Language=Javascript>
function CompareDates()
{
var str1 = document.getElementById("Fromdate").value;
var str2 = document.getElementById("Todate").value;
var dt1 = parseInt(str1.substring(0,2),10);
var mon1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var dt2 = parseInt(str2.substring(0,2),10);
var mon2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 < date1)
{
alert("To date cannot be greater than from date");
return false;
}
else
{
alert("Submitting ...");
}
}
</Script>
Hope it will work 4 u...
If I have two dates, how can I use JavaScript to get the difference between the two dates in minutes?
You may checkout this code:
var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");
or var diffMins = Math.floor((... to discard seconds if you don't want to round minutes.
Subtracting two Date objects gives you the difference in milliseconds, e.g.:
var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));
Math.abs is used to be able to use the absolute difference (so new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00') gives the same result).
Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes. To round to whole minutes, use Math.floor or Math.ceil:
var minutes = Math.floor((diff/1000)/60);
In this example the result will be 720.
[edit 2022] Added a more complete demo snippet, using the aforementioned knowledge.
See also
untilXMas();
function difference2Parts(milliseconds) {
const secs = Math.floor(Math.abs(milliseconds) / 1000);
const mins = Math.floor(secs / 60);
const hours = Math.floor(mins / 60);
const days = Math.floor(hours / 24);
const millisecs = Math.floor(Math.abs(milliseconds)) % 1000;
const multiple = (term, n) => n !== 1 ? `${n} ${term}s` : `1 ${term}`;
return {
days: days,
hours: hours % 24,
hoursTotal: hours,
minutesTotal: mins,
minutes: mins % 60,
seconds: secs % 60,
secondsTotal: secs,
milliSeconds: millisecs,
get diffStr() {
return `${multiple(`day`, this.days)}, ${
multiple(`hour`, this.hours)}, ${
multiple(`minute`, this.minutes)} and ${
multiple(`second`, this.seconds)}`;
},
get diffStrMs() {
return `${this.diffStr.replace(` and`, `, `)} and ${
multiple(`millisecond`, this.milliSeconds)}`;
},
};
}
function untilXMas() {
const nextChristmas = new Date(Date.UTC(new Date().getFullYear(), 11, 25));
const report = document.querySelector(`#nextXMas`);
const diff = () => {
const diffs = difference2Parts(nextChristmas - new Date());
report.innerHTML = `Awaiting next XMas 🙂 (${
diffs.diffStrMs.replace(/(\d+)/g, a => `<b>${a}</b>`)})<br>
<br>In other words, until next XMas lasts…<br>
In minutes: <b>${diffs.minutesTotal}</b><br>In hours: <b>${
diffs.hoursTotal}</b><br>In seconds: <b>${diffs.secondsTotal}</b>`;
setTimeout(diff, 200);
};
return diff();
}
body {
font: 14px/17px normal verdana, arial;
margin: 1rem;
}
<div id="nextXMas"></div>
var startTime = new Date('2012/10/09 12:00');
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);
A simple function to perform this calculation:
function getMinutesBetweenDates(startDate, endDate) {
var diff = endDate.getTime() - startDate.getTime();
return (diff / 60000);
}
That's should show the difference between the two dates in minutes. Try it in your browser:
const currDate = new Date('Tue Feb 13 2018 13:04:58 GMT+0200 (EET)')
const oldDate = new Date('Tue Feb 13 2018 12:00:58 GMT+0200 (EET)')
(currDate - oldDate) / 60000 // 64
This problem is solved easily with moment.js, like this example:
var difference = mostDate.diff(minorDate, "minutes");
The second parameter can be changed for another parameters, see the moment.js documentation.
e.g.: "days", "hours", "minutes", etc.
http://momentjs.com/docs/
The CDN for moment.js is available here:
https://cdnjs.com/libraries/moment.js
Thanks.
EDIT:
mostDate and minorDate should be a moment type.
EDIT 2:
For those who are reading my answer in 2020+, momentjs is now a legacy project.
If you are still looking for a well-known library to do this job, I would recommend date-fns.
// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
new Date(2014, 6, 2, 12, 20, 0),
new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12
You can do as follows:
Get difference of dates(Difference will be in milliseconds)
Convert milliseconds into minutes i-e ms/1000/60
The Code:
let dateOne = new Date("2020-07-10");
let dateTwo = new Date("2020-07-11");
let msDifference = dateTwo - dateOne;
let minutes = Math.floor(msDifference/1000/60);
console.log("Minutes between two dates =",minutes);
For those that like to work with small numbers
const today = new Date();
const endDate = new Date(startDate.setDate(startDate.getDate() + 7));
const days = parseInt((endDate - today) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(endDate - today) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000) % 60);
Here's some fun I had solving something similar in node.
function formatTimeDiff(date1, date2) {
return Array(3)
.fill([3600, date1.getTime() - date2.getTime()])
.map((v, i, a) => {
a[i+1] = [a[i][0]/60, ((v[1] / (v[0] * 1000)) % 1) * (v[0] * 1000)];
return `0${Math.floor(v[1] / (v[0] * 1000))}`.slice(-2);
}).join(':');
}
const millis = 1000;
const utcEnd = new Date(1541424202 * millis);
const utcStart = new Date(1541389579 * millis);
const utcDiff = formatTimeDiff(utcEnd, utcStart);
console.log(`Dates:
Start : ${utcStart}
Stop : ${utcEnd}
Elapsed : ${utcDiff}
`);
/*
Outputs:
Dates:
Start : Mon Nov 05 2018 03:46:19 GMT+0000 (UTC)
Stop : Mon Nov 05 2018 13:23:22 GMT+0000 (UTC)
Elapsed : 09:37:02
*/
You can see it in action at https://repl.it/#GioCirque/TimeSpan-Formatting
The following code worked for me,
function timeDiffCalc(dateNow,dateFuture) {
var newYear1 = new Date(dateNow);
var newYear2 = new Date(dateFuture);
var dif = (newYear2 - newYear1);
var dif = Math.round((dif/1000)/60);
console.log(dif);
}
It works easily:
var endTime = $("#ExamEndTime").val();
var startTime = $("#ExamStartTime").val();
//create date format
var timeStart = new Date("01/01/2007 " + startTime);
var timeEnd = new Date("01/01/2007 " + endTime);
var msInMinute = 60 * 1000;
var difference = Math.round(Math.abs(timeEnd - timeStart) / msInMinute);
$("#txtCalculate").val(difference);
this will work
duration = moment.duration(moment(end_time).diff(moment(start_time)))