Search code examples
javascriptmysqldatetimecountdown

JavaScript countdown to MySQL datetime format


I have a date that comes from a MySQL database in the datetime format, something like 2010-09-24 11:30:12. And I need a way to show a countdown of hours:mins to that date.

I'm not very familiar with dates in JavaScript so any help would be apreciated. Thanks.


Solution

  • 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