I have an event, this events date and time is formatted to be of type unix timestamp.
In JavaScript (not looking for a plugin approach, such as modern.js
), I'm now trying to determine the time difference between todays date and the event date.
I'm looking to implement a "countdown to event" feature which will countdown the days, hours, minutes and seconds to the event date.
{{ event_date_and_time }}
in my code below is a HuBL
variable.
Current approach:
var todays_date = new Date().getTime() / 1000;
var event_date = new Date({{ event_date_and_time }}).getTime() / 1000
var start = todays_date;
var end = event_date;
console.log(todays_date); // this logs "1596626215.983"
console.log(end); // this logs "1596888000"
function timeDifference(date1,date2) {
var difference = date1 - date2;
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);
console.log('difference = ' +
daysDifference + ' day/s ' +
hoursDifference + ' hour/s ' +
minutesDifference + ' minute/s ' +
secondsDifference + ' second/s ');
}
timeDifference(start, end);
So, the time of my test was 12:15pm (todays_date
). The event date is set to 8th August 12:00pm.
The results I'm getting with the above is:
difference = -1 day/s 23 hour/s 55 minute/s 38 second/s
Which is obviously wrong, where am I going wrong?