Hello-World
Hello-World

Reputation: 9555

compare sql date to javascript date

Is there an easy way to compare a sql dateTime to a javascript date time so that the two can be compared easily?

Are there built in javascript functions as I cant edit the sql

Upvotes: 3

Views: 13060

Answers (4)

Cees Timmerman
Cees Timmerman

Reputation: 19644

Assuming that date string comes from SQL:

>>> new Date('2012-11-10 15:16:17')
Date {Invalid Date}

>>> new Date('2012-11-10T15:16:17')
Date {Sat Nov 10 2012 15:16:17 GMT+0100}

>>> new Date('2012-11-10 15:16:17'.replace(' ', 'T'))
Date {Sat Nov 10 2012 15:16:17 GMT+0100}

You can handle input from any timezone by appending the offset, like this for London time:

>>> new Date('2012-11-10 15:16:17'.replace(' ', 'T') + '+00:00')
Date {Sat Nov 10 2012 16:16:17 GMT+0100}

To compare two dates in JavaScript, simply subtract them to return the difference in milliseconds:

>>> var d1 = new Date('2012-11-10T15:16:17'); var d2 = new Date('2012-11-10T15:16:18'); d2 - d1
1000

Here's a nice class to compare by months and such.

Upvotes: 5

user2195796
user2195796

Reputation: 11

to fix parseInt(08) and parseInt(09), use parseInt(08,10) parseInt(09,10).

In Javascript numbers starting with zero are considered octal and there's no 08 or 09 in octal, hence the problem.

http://www.ventanazul.com/webzine/articles/issues-parseint-javascript

Upvotes: 1

Michael Besteck
Michael Besteck

Reputation: 2423

To convert a MySQL DATETIME String into a JavaScript Date object:

        var sqlDateStr = "2012-01-02 23:58:59"; // as for MySQL DATETIME
        sqlDateStr = sqlDateStr.replace(/:| /g,"-");
        var YMDhms = sqlDateStr.split("-");
        var sqlDate = new Date();
        sqlDate.setFullYear(parseInt(YMDhms[0]), parseInt(YMDhms[1])-1,
                                                 parseInt(YMDhms[2]));
        sqlDate.setHours(parseInt(YMDhms[3]), parseInt(YMDhms[4]), 
                                              parseInt(YMDhms[5]), 0/*msValue*/);
        alert(sqlDate);

Upvotes: 2

Amith George
Amith George

Reputation: 5916

How are you accessing the sql datetime in javascript. Am assuming you have it as a string. The builtin js Date.parse() function can parse a variety of string and return a js Date object.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse

If your sql date is being returned in a custom format, you will need to manually break it down into the relevant year, month, date, hours, min, second components and assemble the Date object using the appropriate Date() constructor.

Upvotes: 0

Related Questions