解析日期格式不同的通用方法 [英] generic method to parse date with different formats

查看:102
本文介绍了解析日期格式不同的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个 javascript checkDateFormat 函数,该函数需要两个字符串参数:

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


  1. 日期字符串

  2. 格式化字符串

它应该检查日期字符串是否根据格式字符串正确格式化。

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

例如:

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 ?

谢谢。

推荐答案

也许这就是您想要的吗?

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

这篇关于解析日期格式不同的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆