Validate two dates of this “dd-MMM-yyyy” format in javascript

前端 未结 5 1456
时光取名叫无心
时光取名叫无心 2020-12-21 08:33

I have two dates 18-Aug-2010 and 19-Aug-2010 of this format. How to find whether which date is greater?

5条回答
  •  Happy的楠姐
    2020-12-21 09:16

    Firstly, the 'dd-MMM-yyyy' format isn't an accepted input format of the Date constructor (it returns an "invalid date" object) so we need to parse this ourselves. Let's write a function to return a Date object from a string in this format.

    function parseMyDate(s) {
        var m = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
        var match = s.match(/(\d+)-([^.]+)-(\d+)/);
        var date = match[1];
        var monthText = match[2];
        var year = match[3];
        var month = m.indexOf(monthText.toLowerCase());
        return new Date(year, month, date);
    }

    Date objects implicitly typecast to a number (milliseconds since 1970; epoch time) so you can compare using normal comparison operators:

    if (parseMyDate(date1) > parseMyDate(date2)) ...

提交回复
热议问题