You may want to use the UNIX_TIMESTAMP()
function in MySQL to return your date in Unix Time Format (the number of seconds since January 1, 1970). Let's say our target date is '2011-01-01 00:00:00'
(in reality you would probably have a field from your table, instead of a constant):
SELECT UNIX_TIMESTAMP('2011-01-01 00:00:00') AS timestamp;
+---------------+
| timestamp |
+---------------+
| 1293836400 |
+---------------+
1 row in set (0.00 sec)
Then we can use the getTime()
method of the Date
object in JavaScript to calculate the number of seconds between the current time and the target time. Once we have the number of seconds, we can easily calculate the hours, minutes and days:
var target = 1293836400; // We got this from MySQL
var now = new Date(); // The current tume
var seconds_remaining = target - (now.getTime() / 1000).toFixed(0);
var minutes_remaining = seconds_remaining / 60;
var hours_remaining = minutes_remaining / 60;
var days_remaining = hours_remaining / 24;
alert(seconds_remaining + ' seconds'); // 8422281 seconds
alert(minutes_remaining + ' minutes'); // 140371.35 minutes
alert(hours_remaining + ' hours'); // 2339.5225 hours
alert(days_remaining + ' days'); // 97.48010416666666 days