Not counting down time correctly - javascript

I am creating a countdown website. I want it to count down from the current time the my celebration date 2019-11-29 00:00:00. I want the timezone to be in Australia Brisbane time zone. However, it seems to be that it keeps calculating the amount of time left till my celebration date wrong. Could someone tell me what I did wrong? And once the time hits 0, how can I get rid of the countdown and replace it with Its celebration time
function dateDiff(a, b) {
// Some utility functions:
const getSecs = dt => (dt.getHours() * 24 + dt.getMinutes()) * 60 + dt.getSeconds();
const getMonths = dt => dt.getFullYear() * 12 + dt.getMonth();
// 0. Convert to new date objects to avoid side effects
a = new Date(a);
b = new Date(b);
if (a > b) [a, b] = [b, a]; // Swap into order
// 1. Get difference in number of seconds during the day:
let diff = getSecs(b) - getSecs(a);
if (diff < 0) {
b.setDate(b.getDate()-1); // go back one day
diff += 24*60*60; // compensate with the equivalent of one day
}
// 2. Get difference in number of days of the month
let days = b.getDate() - a.getDate();
if (days < 0) {
b.setDate(0); // go back to (last day of) previous month
days += b.getDate(); // compensate with the equivalent of one month
}
// 3. Get difference in number of months
const months = getMonths(b) - getMonths(a);
return {
years: Math.floor(months/12),
months: months % 12,
days,
hours: Math.floor(diff/3600),
minutes: Math.floor(diff/60) % 24,
seconds: diff % 60
};
}
// Date to start on
var celebrationDate = new Date("2019-11-29 00:00:00").toLocaleString("en-US", {timeZone: "Australia/Brisbane"});
// Update the count every 1 second
!function refresh () {
const diff = dateDiff(new Date().toLocaleString("en-US", {timeZone: "Australia/Brisbane"}), celebrationDate);
document.getElementById("day-val").innerHTML = diff[Object.keys(diff)[2]];
document.getElementById("hour-val").innerHTML = diff[Object.keys(diff)[3]];
document.getElementById("min-val").innerHTML = diff[Object.keys(diff)[4]];
document.getElementById("sec-val").innerHTML = diff[Object.keys(diff)[5]];
setTimeout(refresh, 1000)
}()
<div id="day-val"></div><div>Days</div><br>
<div id="hour-val"></div><div>Hours</div><br>
<div id="min-val"></div><div>Minutes</div><br>
<div id="sec-val"></div><div>Seconds</div>

IF you are using moment.js
What you can do is use the diff and duration functions like so:
const now = moment();
const celebrationDate= moment("2019-11-30 00:00:00");
// this will get the difference between now and celebrationDate
const celebrationDateDiff = expiration.diff(now);
// convert it into duration
const duration = moment.duration(celebrationDateDiff);
You can then access the countdown like:
duration.days() // will return the number of days
duration.hours() // will return the number of remaining hours
duration.minutes() // will return the number of remaining minutes

Solution with plain javascript:
Get the clients time zone offset
Calculate the diff between client offset and "Australian/Brisbane" offset
Calculate time left by targetDate - currentDate - offsetDiff
Format the result to display it
Example:
const minToMS = min => min * 60 * 1000
const getCountDownFromMS = diff => {
const milliseconds = diff % 1000
diff = (diff - milliseconds) / 1000
const seconds = diff % 60
diff = (diff - seconds) / 60
const minutes = diff % 60
diff = (diff - minutes) / 60
const hours = diff % 24
diff = (diff - hours) / 24
const days = diff
return {
days,
hours,
minutes,
seconds,
milliseconds
}
}
const targetDate = new Date('2019-11-29 00:00:00')
// Getting offset with getTimezoneOffset is not reliable, using a database to get time zone offset is needed, like IANA Time Zone Database.
// moment.js internally uses IANA db
const tzOffset = targetDate.getTimezoneOffset() // Client browsers timezone offset in minutes
const target_tzOffset = -600 // Australia Brisbane timezone offset in minutes
const offset = minToMS(tzOffset - target_tzOffset)
const msLeft = targetDate - new Date() - offset
const result = getCountDownFromMS(msLeft)
You should also check moment.js as it has many useful features.
Example with moment.js:
const now = moment()
const target = moment.tz('2019-11-29 00:00:00', 'Australia/Brisbane')
const result = moment.duration(target.diff(now))

Related

How to get the remaining time from 24 hours in JavaScript

I have a problem, where I try to find the number of hours and minutes after I had last collected the item. For example, if I had collected the item 1 minute ago, the code should be able to print out the remaining time left to collect the item again(23 h and 59 m) in this format. Till now, I have worked out this much:
UserJSON is a JSON file with the user's name and the time of their last claim
let deltaHour = Math.floor(new Date().getTime() - UserJSON[message.author.id].lastclaim) / (60 * 60 * 24)
let deltaRealHour = Math.floor(deltaHour)
let deltaMin = ((deltaHour % 1) / 100) * 60
Please help me out.
Here is a possible solution.
You can use the function I wrote before (timeUntilNextClaim()), supply it with the last time that your user claimed the item (in epoch seconds) and it will return to you the delta milliseconds until the item can be claimed.
You can then use the second funciton I wrote for you (toHrsAndMinutes) to turn milliseconds into hours and minutes (rounded down of course).
Please let me know if you have any questions or would like any more help with this. I'd be happy to help.
function timeUntilNextClaim(LastClaim) {
/* this function takes an epoch time of the
last time the user claimed the item as an argument and
returns (in ms) the time until they can pick up the
item again */
let now = new Date();
// add 24 hours to last claim time to calculate next claim time
let timeTilClaim = (LastClaim + 8.64e7) - now;
if (timeTilClaim <= 0) {
return 0;
} else {
return timeTilClaim;
}
}
function toHrsAndMinutes(duration) {
// this function will return an array of [hours, minutes] of a duration specified in ms
var hours, minutes;
hours = Math.floor(duration / 3.6e6);
minutes = Math.floor((duration % 3.6e6) / 60000);
return [hours, minutes];
}
function test() {
// tests / Example Usage
let usrLastClaimTime = new Date() - 20160000; // lets pretend they claimed it last 5.6 hours ago
let now = new Date();
let msTilNextClaim = timeUntilNextClaim(usrLastClaimTime);
let hoursTilClaim, minsTilClaim;
[hoursTilClaim, minsTilClaim] = toHrsAndMinutes(msTilNextClaim);
console.log(`The current time is ${now}`);
console.log(`The item was last claimed at ${Date(usrLastClaimTime)}`);
console.log(`You can claim again in ${hoursTilClaim} Hours and ${minsTilClaim} Minutes`);
}
test();
getTime() is milliseconds since Jan 1, 1970, 00:00:00.000 GMT
let lastclaim = 1632196398605;
let delta = (new Date() - new Date(lastclaim)) / (60 * 1000 * 60);
let deltaHrs = Math.floor(delta);
let deltaMins = Math.floor((delta % 1) * 60);
console.log(`deltaHrs:`, deltaHrs);
console.log(`deltaMins:`, deltaMins);

How to get times from a number of slots

I'm trying to get times of available slots. I have startDateTime, endDateTime, duration, and bufferBetweenSlots fields in my db. with some calculations I have figured out number of available slots.
the value of fields are:
startDateTime: 8/20/2021 11:30 AM
endDateTime: 8/20/2021 9:30 PM
duration: 60
bufferBetweenSlots: 30
but I'm not sure how to get the start and end time for the available slots. e.g. 10:00 - 11:00
const getTimeDiffInMins = (endTime, startTime) =>
(+new Date(endTime) - +new Date(startTime)) / (60 * 1000);
const getMultipleTimeSlots = (data) => {
const diff = getTimeDiffInMins(data.end_date_time, data.start_date_time);
const totalSlots = diff / data.duration;
const totalBuffer = data.buffer_between_slots * totalSlots;
const availableSlots = (diff - totalBuffer) / 60;
return availableSlots;
};
any suggestions?
You should only need a buffer between slots, so the number of buffers is one less than the number of slots, i.e. you want to solve:
n * slotTime + (n - 1) * bufferTime == totalTime
such that:
totalTime <= diff
You can do that by adding the buffer to totalTime and dividing by slotTime + bufferTime, then flooring the result to get the whole number of available slots plus buffers. Then you can just iterate to produce the required start and end time. E.g.
let startDateTime = new Date(2021,7,8,11,30); // 20 Aug 2021 11:30
let endDateTime = new Date(2021,7,8,22); // 20 Aug 2021 22:00
let duration = 60; // minutes
let bufferBetweenSlots = 30; // minutes
let diff = (endDateTime - startDateTime) / 6e4; // minutes
let numberOfSlots = Math.floor((diff + bufferBetweenSlots) / (duration + bufferBetweenSlots)); // minutes
let slots = [];
let time = new Date(startDateTime);
for (let i = 0; i < numberOfSlots; i++) {
// Add the slot start time
slots[i] = {start: time.toString()};
// Increment time to end of slot
time.setMinutes(time.getMinutes() + duration);
// Add the end time
slots[i].end = time.toString();
// Increment time to end of buffer
time.setMinutes(time.getMinutes() + bufferBetweenSlots);
}
console.log(slots);
I changed the end time to 22:00 to show it only puts in full slots. Whether you push timestamps or Date objects into the slots array is up to you. Just remember, if adding dates, to copy the date like:
slots[i] = {start: new Date(+time)};
...
slots[i].end = new Date(+time);
Thanks #RobG for taking the time to answer. here's how I managed to slove it.
const getTimeDiffInMins = (endTime, startTime) =>
(+new Date(endTime) - +new Date(startTime)) / (60 * 1000);
const convertToMilliSecs = (value) => value * 60 * 1000;
// coming from the db
const data = {
duration: 60,
buffer_between_slots: 30,
start_date_time: '2021-08-20T10:30:00Z',
end_date_time: '2021-08-20T20:30:00Z',
};
const {
duration: a,
buffer_between_slots: b,
end_date_time: x,
start_date_time: y,
} = data;
const duration = getTimeDiffInMins(x, y);
const slotDuration = a;
const totalSlots = a + b;
const numberOfSlots = Math.floor(duration / totalSlots);
const slotsAvailable = [...Array(numberOfSlots).keys()].map((slotNumber) => {
const slotStart = (slotNumber - 1) * totalSlots;
const slotEnd = slotStart + slotDuration;
return {
start: +new Date(y) + convertToMilliSecs(slotStart),
end: +new Date(y) + convertToMilliSecs(slotEnd),
};
});
/*
Now we can format the time however we want
I'm using momentjs:
moment(new Date(slot.start)).format('h:mma')
*/
console.log(slotsAvailable);

Calculate total number of weeks and days between two dates? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 8 years ago.
I am calculating the number of days between the 'from' and 'to' date. For example, if the from date is 13/04/2010 and the to date is 15/04/2010 the result should be
How do I get the result using JavaScript?
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
Here is a function that does this:
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.
var nDays = ( Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;
as a function:
function DaysBetween(StartDate, EndDate) {
// The number of milliseconds in all UTC days (no DST)
const oneDay = 1000 * 60 * 60 * 24;
// A day in UTC always lasts 24 hours (unlike in other time formats)
const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());
// so it's safe to divide by 24 hours
return (start - end) / oneDay;
}
Here is my implementation:
function daysBetween(one, another) {
return Math.round(Math.abs((+one) - (+another))/8.64e7);
}
+<date> does the type coercion to the integer representation and has the same effect as <date>.getTime() and 8.64e7 is the number of milliseconds in a day.
Adjusted to allow for daylight saving differences. try this:
function daysBetween(date1, date2) {
// adjust diff for for daylight savings
var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
// apply the tz offset
date2.addHours(hoursToAdjust);
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
// you'll want this addHours function too
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
I have written this solution for another post who asked, how to calculate the difference between two dates, so I share what I have prepared:
// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
alert(timeDifferenceInDays);
You can skip some steps in the code, I have written it so to make it easy to understand.
You'll find a running example here: http://jsfiddle.net/matKX/
From my little date difference calculator:
var startDate = new Date(2000, 1-1, 1); // 2000-01-01
var endDate = new Date(); // Today
// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
var ndays;
var tv1 = d1.valueOf(); // msec since 1970
var tv2 = d2.valueOf();
ndays = (tv2 - tv1) / 1000 / 86400;
ndays = Math.round(ndays - 0.5);
return ndays;
}
So you would call:
var nDays = diffDays(startDate, endDate);
(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)
Addendum
The code can be improved by changing these lines:
var tv1 = d1.getTime(); // msec since 1970
var tv2 = d2.getTime();

How to round time to the nearest quarter hour in JavaScript?

For example:
Given time: 08:22 => Rounded to: 08:15
Given time: 08:23 => Rounded to: 08:30
Should be pretty simple. But all I was able to produce is lengthy, not very good code to solve the issue. My mind's just gone blank.
Regards
Given that you have hours and minutes in variables (if you don't you can get them from the Date instance anyway by using Date instance functions):
var m = (parseInt((minutes + 7.5)/15) * 15) % 60;
var h = minutes > 52 ? (hours === 23 ? 0 : ++hours) : hours;
minutes can as well be calculated by using Math.round():
var m = (Math.round(minutes/15) * 15) % 60;
or doing it in a more javascript-sophisticated expression without any functions:
var m = (((minutes + 7.5)/15 | 0) * 15) % 60;
var h = ((((minutes/105) + .5) | 0) + hours) % 24;
You can check the jsPerf test that shows Math.round() is the slowest of the three while mainly the last one being the fastest as it's just an expression without any function calls (no function call overhead i.e. stack manipulation, although native functions may be treated differently in Javascript VM).
//----
This function round the time to the nearest quarter hour.
function roundTimeQuarterHour(time) {
var timeToReturn = new Date(time);
timeToReturn.setMilliseconds(Math.round(timeToReturn.getMilliseconds() / 1000) * 1000);
timeToReturn.setSeconds(Math.round(timeToReturn.getSeconds() / 60) * 60);
timeToReturn.setMinutes(Math.round(timeToReturn.getMinutes() / 15) * 15);
return timeToReturn;
}
With Time String
Here is a method that will round a time string like the one you presented. Eg "08:22"
let roundTime = (time, minutesToRound) => {
let [hours, minutes] = time.split(':');
hours = parseInt(hours);
minutes = parseInt(minutes);
// Convert hours and minutes to time in minutes
time = (hours * 60) + minutes;
let rounded = Math.round(time / minutesToRound) * minutesToRound;
let rHr = ''+Math.floor(rounded / 60)
let rMin = ''+ rounded % 60
return rHr.padStart(2, '0')+':'+rMin.padStart(2, '0')
}
// USAGE //
// Round time to 15 minutes
roundTime('8:07', 15); // "08:00"
roundTime('7:53', 15); // "08:00"
roundTime('7:52', 15); // "07:45"
With Hours and Minutes Already Split Up
You can use this method if you don't need to parse out the hour and minute strings like your example shows
let roundTime = (hours, minutes, minutesToRound) => {
// Convert hours and minutes to minutes
time = (hours * 60) + minutes;
let rounded = Math.round(time / minutesToRound) * minutesToRound;
let roundedHours = Math.floor(rounded / 60)
let roundedMinutes = rounded % 60
return { hours: roundedHours, minutes: roundedMinutes }
}
// USAGE //
// Round time to 15 minutes
roundTime(7, 52, 15); // {hours: 7, minutes: 45}
roundTime(7, 53, 15); // {hours: 8, minutes: 0}
roundTime(1, 10, 15); // {hours: 1, minutes: 15}
With Existing Date Object
Or, if you are looking to round an already existing date object to the nearest x minutes, you can use this method.
If you don't give it any date it will round the current time. In your case, you can round to the nearest 15 minutes.
let getRoundedDate = (minutes, d=new Date()) => {
let ms = 1000 * 60 * minutes; // convert minutes to ms
let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
return roundedDate
}
// USAGE //
// Round existing date to 5 minutes
getRoundedDate(15, new Date()); // 2018-01-26T00:45:00.000Z
// Get current time rounded to 30 minutes
getRoundedDate(30); // 2018-01-26T00:30:00.000Z
The code here is a little verbose but I'm sure you'll see how you could combine the lines to make this shorter. I've left it this way to clearly show the steps:
var now = new Date();
var mins = now.getMinutes();
var quarterHours = Math.round(mins/15);
if (quarterHours == 4)
{
now.setHours(now.getHours()+1);
}
var rounded = (quarterHours*15)%60;
now.setMinutes(rounded);
document.write(now);
Divide by 9e5 milliseconds (15 * 60 * 1000), round, and multiply back by 9e5 :
const roundToQuarter = date => new Date(Math.round(date / 9e5) * 9e5)
console.log( roundToQuarter(new Date("1999-12-31T23:52:29.999Z")) ) // 1999-12-31T23:45:00
console.log( roundToQuarter(new Date("1999-12-31T23:52:30.000Z")) ) // 2000-01-01T00:00:00
console.log( roundToQuarter(new Date) )
I use these code:
function RoundUp(intervalMilliseconds, datetime){
datetime = datetime || new Date();
var modTicks = datetime.getTime() % intervalMilliseconds;
var delta = modTicks === 0 ? 0 : datetime.getTime() - modTicks;
delta += intervalMilliseconds;
return new Date(delta);
}
function RoundDown(intervalMilliseconds, datetime){
datetime = datetime || new Date();
var modTicks = datetime.getTime() % intervalMilliseconds;
var delta = modTicks === 0 ? 0 : datetime.getTime() - modTicks;
return new Date(delta);
}
function Round(intervalMilliseconds, datetime){
datetime = datetime || new Date();
var modTicks = datetime.getTime() % intervalMilliseconds;
var delta = modTicks === 0 ? 0 : datetime.getTime() - modTicks;
var shouldRoundUp = modTicks > intervalMilliseconds/2;
delta += shouldRoundUp ? intervalMilliseconds : 0;
return new Date(delta);
}
Round to the nearest 5 minutes:
//with current datetime
var result = Round(5 * 60 * 1000);
//with a given datetime
var dt = new Date();
var result = Round(5 * 60 * 1000, dt);
There is an NPM package #qc/date-round that can be used. Given that you have a Date instance to be rounded
import { round } from '#qc/date-round'
const dateIn = ...; // The date to be rounded
const interval = 15 * 60 * 1000; // 15 minutes (aka quarter hour)
const dateOut = round(dateIn, interval)
Then you can use date-fns to format the date
import format from 'date-fns/format';
console.log(format(dateOut, 'HH:mm')) // 24-hr
console.log(format(dateOut, 'hh:mm a')) // 12-hr
Another one with date-fns (not mandatory)
import {getMinutes, setMinutes, setSeconds, setMilliseconds} from 'date-fns'
let date = new Date();
let min = getMinutes(date);
let interval = 3 // in minutes
let new_min = min - min%interval + interval;
let new_date = setMilliseconds(setSeconds(setMinutes(date,new_min),0),0)
console.log('Orignal Date : ' + date);
console.log('Original Minute : ' + min);
console.log('New Minute : ' + new_min);
console.log('New Date : ' + new_date);
Pass the interval in milliseconds get the next cycle in roundUp order
Example if I want next 15 minute cycle from current time then call this method like *calculateNextCycle(15 * 60 * 1000);*
Samething for quarter hour pass the interval
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(15 * 60 * 1000));
This method is specifically for Vue.js, it takes a time, and returns to the nearest entered increment, I based this on an above answer, but this is for Vue specifically using echma-6 standards. It will return T:06:00:00, if you fed 06:05 into it. This is used specifically with vuetify's v-calendar to choose a time in weeklyor daily format.
This answer also adds the 0 for like 06 hrs. Which is where this differs from the above answers. If you change the 30 to 15
methods: {
roundTimeAndFormat(datetime, roundTo) {
const hrsMins = datetime.split(':')
let min = ((((hrsMins[1] + 7.5) / roundTo) | 0) * roundTo) % 60
let hr = (((hrsMins[1] / 105 + 0.5) | 0) + hrsMins[0]) % 24
if (Number(hr) < 10) {
hr = ('0' + hr).slice(-2)
}
if (min === 0) {
min = ('0' + min).slice(-2)
}
return 'T' + hr + ':' + min + ':00'
}
}
You would just call:
this.roundTimeAndFormat(dateTime, 15)
And you would get the time to the nearest 15min interval.
If you enter, 11:01, you'd get T11:00:00
Might help others. For any language. Mainly trick with round function.
roundedMinutes = yourRoundFun(Minutes / interval) * interval
E.g. The interval could be 5 minutes, 10 minutes, 15 minutes, 30 minutes.
Then rounded minutes can be reset to the respective date.
yourDateObj.setMinutes(0)
yourDateObj.setMinutes(roundedMinutes)
also if required then
yourDateObj.setSeconds(0)
yourDateObj.setMilliSeconds(0)
Simple?

How to calculate the number of days between two dates? [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 8 years ago.
I am calculating the number of days between the 'from' and 'to' date. For example, if the from date is 13/04/2010 and the to date is 15/04/2010 the result should be
How do I get the result using JavaScript?
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2008, 1, 12);
const secondDate = new Date(2008, 1, 22);
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
Here is a function that does this:
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.
var nDays = ( Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;
as a function:
function DaysBetween(StartDate, EndDate) {
// The number of milliseconds in all UTC days (no DST)
const oneDay = 1000 * 60 * 60 * 24;
// A day in UTC always lasts 24 hours (unlike in other time formats)
const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());
// so it's safe to divide by 24 hours
return (start - end) / oneDay;
}
Here is my implementation:
function daysBetween(one, another) {
return Math.round(Math.abs((+one) - (+another))/8.64e7);
}
+<date> does the type coercion to the integer representation and has the same effect as <date>.getTime() and 8.64e7 is the number of milliseconds in a day.
Adjusted to allow for daylight saving differences. try this:
function daysBetween(date1, date2) {
// adjust diff for for daylight savings
var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
// apply the tz offset
date2.addHours(hoursToAdjust);
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
// you'll want this addHours function too
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
I have written this solution for another post who asked, how to calculate the difference between two dates, so I share what I have prepared:
// Here are the two dates to compare
var date1 = '2011-12-24';
var date2 = '2012-01-01';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// and finaly, in days :)
var timeDifferenceInDays = timeDifferenceInHours / 24;
alert(timeDifferenceInDays);
You can skip some steps in the code, I have written it so to make it easy to understand.
You'll find a running example here: http://jsfiddle.net/matKX/
From my little date difference calculator:
var startDate = new Date(2000, 1-1, 1); // 2000-01-01
var endDate = new Date(); // Today
// Calculate the difference of two dates in total days
function diffDays(d1, d2)
{
var ndays;
var tv1 = d1.valueOf(); // msec since 1970
var tv2 = d2.valueOf();
ndays = (tv2 - tv1) / 1000 / 86400;
ndays = Math.round(ndays - 0.5);
return ndays;
}
So you would call:
var nDays = diffDays(startDate, endDate);
(Full source at http://david.tribble.com/src/javascript/jstimespan.html.)
Addendum
The code can be improved by changing these lines:
var tv1 = d1.getTime(); // msec since 1970
var tv2 = d2.getTime();

Categories

Resources