Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JS - How to compare two date/time stamps?

I have two date/time stamps:

d1 = 2011-03-02T15:30:18-08:00 
d2 = 2011-03-02T15:36:05-08:00

I want to be above to compare the two:

if (new Date(d1) < new Date(d2)) {alert('newer')}

But that does not appear to be working correctly. Is there a way to compare not just the dates but the times as well.? thanks

UPDATE:

console.log(d1 + ' ' + d2);
console.log(new Date(d1) > new Date(d2))


2011-03-02T15:30:18-08:00 2011-03-02T15:36:05-08:00
false
2011-03-02T15:30:18-08:00 2011-03-02T15:30:18-08:00
false
2011-03-02T15:30:18-08:00 2011-03-02T14:15:04-08:00
false
like image 309
AnApprentice Avatar asked Nov 28 '22 18:11

AnApprentice


2 Answers

Your timestamps should be strings.

var d1 = "2011-03-02T15:30:18-08:00";
var d2 = "2011-03-02T15:36:05-08:00";

if (new Date(d1) < new Date(d2)) {alert('newer')}

Example: http://jsfiddle.net/hKPkF/

like image 110
user113716 Avatar answered Dec 11 '22 04:12

user113716


You may be having trouble with the date string format. I am getting Invalid date if I do:

new Date("2011-03-02T15:30:18-08:00");

Here's what works for me on Chrome:

var d1 = "Thu Mar 03 2011 00:53:54 GMT+0100 (CET)";
var d2 = "Thu Mar 03 2011 03:53:54 GMT+0100 (CET)";

if (new Date(d1) < new Date(d2)) {console.log('newer')}

If you are working in ruby on the server side, you could convert to UTC from a Time object. Here it is, with a little massaging to convert to a format that is identical to javascript's Date object toUTCString method:

tm = Time.new
utc_tm = tm.getutc
utc_tm.strftime("%a, %d %b %Y %H:%M:%S GMT")

Output: "Thu, 03 Mar 2011 00:46:55 GMT"

like image 39
madsj Avatar answered Dec 11 '22 04:12

madsj