Comparing two dates with javascript or datejs (date difference)

后端 未结 3 2273
孤街浪徒
孤街浪徒 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.

提交回复
热议问题