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

前端 未结 5 864
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 18:53

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:

5条回答
  •  时光取名叫无心
    2020-12-10 19:33

    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"

提交回复
热议问题