Does anyone can link me to some tutorial where I can find out how to return days , hours , minutes, seconds in javascript between 2 unix datetimes?
I have:
JavaScript
x
3
1
var date_now = unixtimestamp;
2
var date_future = unixtimestamp;
3
I would like to return (live) how many days,hours,minutes,seconds left from the date_now to the date_future.
Advertisement
Answer
Just figure out the difference in seconds (don’t forget JS timestamps are actually measured in milliseconds) and decompose that value:
JavaScript
1
18
18
1
// get total seconds between the times
2
var delta = Math.abs(date_future - date_now) / 1000;
3
4
// calculate (and subtract) whole days
5
var days = Math.floor(delta / 86400);
6
delta -= days * 86400;
7
8
// calculate (and subtract) whole hours
9
var hours = Math.floor(delta / 3600) % 24;
10
delta -= hours * 3600;
11
12
// calculate (and subtract) whole minutes
13
var minutes = Math.floor(delta / 60) % 60;
14
delta -= minutes * 60;
15
16
// what's left is seconds
17
var seconds = delta % 60; // in theory the modulus is not required
18
EDIT code adjusted because I just realised that the original code returned the total number of hours, etc, not the number of hours left after counting whole days.