Number of days between two dates in ISO8601 date format

后端 未结 4 424
谎友^
谎友^ 2021-01-14 17:29

I want to do same thing as How do I get the number of days between two dates in JavaScript?

but I want do the same on this date format: 2000-12-31.

相关标签:
4条回答
  • 2021-01-14 17:50

    Well, it's not jQuery, but just as easy to work with. Check out DateJS. Can parse dates, differences, and more.

    0 讨论(0)
  • 2021-01-14 17:52

    Try this.

    var toDate = "2000-12-31";
    var fromDate = "2000-10-30";
    var diff =  Math.floor(( Date.parse(toDate) - Date.parse(fromDate) ) / 86400000);
    

    You wont be asking this question if you have checked the answer with more up-votes and not the marked answer on the link you have provided. :)

    0 讨论(0)
  • 2021-01-14 17:57

    The other solutions here do not take into account the TimeZone information (which is fine if that is what you want) but I came across a problem like this:
    I have two dates: Thu Mar 01 2012 00:00:00 GMT+0100 and Sat Mar 31 2012 00:00:00 GMT+0200 which will give you 29.95833 days before the Math.floor and hence 29 days after the floor. This is not the 30 days I was expecting. Clearly Daylight Saving has kicked in and shortened one of the days by an hour.

    Here is my solution which takes TimeZones into account:

    function daysBetween(date1String, date2String) {
        var ONE_DAY = 1000 * 60 * 60 * 24;
        var ONE_MINUTE = 1000 * 60;
    
        var d1 = new Date(date1String);
        var d2 = new Date(date2String);
        var d1_ms = d1.getTime() - d1.getTimezoneOffset() * ONE_MINUTE;
        var d2_ms = d2.getTime() - d2.getTimezoneOffset() * ONE_MINUTE;
    
        return Math.floor(d1_ms - d2_ms/ONE_DAY);
    }
    
    0 讨论(0)
  • 2021-01-14 17:59
    function daysBetween(date1String, date2String){
      var d1 = new Date(date1String);
      var d2 = new Date(date2String);
      return (d2-d1)/(1000*3600*24);
    }
    
    console.log( daysBetween('2000-12-31', '2005-05-04') );  //-> 1585
    

    ISO8601 date strings are recognized by JavaScript directly. No need to parse them yourself.

    0 讨论(0)
提交回复
热议问题