generic method to parse date with different format

2019-08-11 21:11发布

I need to create a javascript checkDateFormat function which takes two string arguments:

  1. Date string
  2. Format string

It should check whether the date string is correctly formatted based on the format string.

For example:

checkDateFormat("12-32-2012", "dd-MM-yyyy") // false

The user may change the format string and I need to check the date accordingly.

I have searched a lot but couldn't find a generic function that achieves what I need. Is this achievable or is it necessary to write different implementations for all the possible date formats ?

Thank you.

1条回答
Viruses.
2楼-- · 2019-08-11 21:29

Maybe this does what you want?

function chkdate(datestr,formatstr){
    if (!(datestr && formatstr)) {return false;}
    var splitter = formatstr.match(/\-|\/|\s/) || ['-']
       ,df       = formatstr.split(splitter[0])
       ,ds       = datestr.split(splitter[0])
       ,ymd      = [0,0,0]
       ,dat;
    for (var i=0;i<df.length;i++){
            if (/yyyy/i.test(df[i])) {ymd[0] = ds[i];}
       else if (/mm/i.test(df[i]))   {ymd[1] = ds[i];}
       else if (/dd/i.test(df[i]))   {ymd[2] = ds[i];}
    }
    dat = new Date(ymd.join('/'));
    return !isNaN(dat) && Number(ymd[1])<=12 && dat.getDate()===Number(ymd[2]);
}
//usage
console.log(chkdate ('12/12/2009', 'dd/mm/yyyy')); //=> true
console.log(chkdate ('12/32/2009', 'dd/mm/yyyy')); //=> false
console.log(chkdate ('2002/02/02', 'yyyy-dd-mm')); //=> false
console.log(chkdate ('02-12-2001', 'dd-mm-yyyy')); //=> true
console.log(chkdate ('02-12-2001', 'dd mm yyyy')); //=> false
查看更多
登录 后发表回答