Comparing two dates with javascript or datejs (date difference)

后端 未结 3 2272
孤街浪徒
孤街浪徒 2021-02-20 16:36

I am trying to compare two dates which are in Finnish time form like this: dd.mm.YYYY or d.m.YYYY or dd.m.YYYY or d.mm.YYYY.

I am having a hard time finding out how to d

相关标签:
3条回答
  • 2021-02-20 16:54

    If your dates are strings in the common form d/m/y or some variation thereof, you can use:

    function toDate(s) {
      var s = s.split('/');
      return new Date(s[2], --s[1], s[0]);
    }
    

    You may want to validate the input, or not, depending on how confident you are in the consistency of the supplied data.

    Edit to answer comments

    To permit different separators (e.g. period (.) or hyphen (-)), the regular expression to split on can be:

      var s = s.split(/[/\.-]/);
    

    The date will be split into date, month and year numbers respectively. The parts are passed to the Date constructor to create a local date object for that date. Since javascript months are zero indexed (January is 0, February is 1 and so on) the month number must be reduced by one, hence --s[1].

    /Edit

    To compare two date objects (i.e get the difference in milliseconds) simply subtract one from the other. If you want the result in days, then divide by the number of milliseconds in a day and round (to allow for any minor differences caused by daylight saving).

    So if you want to see how many days are between today and a date, use:

    function diffToToday(s) {
      var today = new Date();
      today.setHours(0,0,0);
      return Math.round((toDate(s) - today) / 8.64e7);
    }
    
    alert(diffToToday('2/8/2011')); // -1
    alert(diffToToday('2/8/2012')); // 365
    

    PS. The "Finnish" data format is the one used by the vast majority of the world that don't use ISO format dates.

    0 讨论(0)
  • 2021-02-20 17:03

    If you are using Datejs, and the optional time.js module, you can run your calculations with the following code by creating a TimeSpan object:

    Example

    // dd.mm.YYYY or d.m.YYYY
    // dd.m.YYYY or d.mm.YYYY
    
    var start = Date.parse("20.09.2011"); 
    var end = Date.parse("28.09.2011");
    
    var span = new TimeSpan(end - start);
    
    span.days; // 8
    

    Of course the above could be simplified down to one line if you really want to be extra terse.

    Example

    new TimeSpan(Date.parse(end) - Date.parse(start)).days; // pass 'end' and 'start' as strings
    

    Hope this helps.

    0 讨论(0)
  • 2021-02-20 17:09

    Using the Date object:

    var today = Date.today();
    var dateToday = Date.parse(today.toString('MMMM d, yyyy'));
    
    var prevMonthDate = dateToday.addDays(-30);
    
    var difference = (dateToday - prevMonthDate)/86400000;
    
    console.log(difference);   //will give you the difference in days. 
    
    0 讨论(0)
提交回复
热议问题