Created
October 10, 2012 12:25
-
-
Save sofish/3865287 to your computer and use it in GitHub Desktop.
detect date type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 仅支持 8 种类型的 day | |
// 20120409 | 2012-04-09 | 2012/04/09 | 2012.04.09 | 以上各种无 0 的状况 | |
var isDate = function (text) { | |
var reg = /^([1-2]\d{3})([-/.])?(1[0-2]|0?[1-9])([-/.])?([1-2]\d|3[01]|0?[1-9])$/ | |
, taste, validDate, yyyy, mm, dd; | |
if (!reg.test(text)) return false; | |
taste = reg.exec(text); | |
year = taste[1], month = taste[3], day = taste[5]; | |
vaildDate = function (year, month, day) { | |
var big = ['1', '3', '5', '7', '8', '10', '12'] | |
// 闰年:四闰百不闰,四百又闰 | |
, isLeap = !(/^\d{2}[0]{2}$/.test(year) ? year % 400 : year % 4) | |
, o = /^0/ | |
, vaildMonth; | |
// 不允许 2012-4-09 这样日期和月份格式不一致的情况 | |
if ((month.length !== day.length && ((month.length === 2 && o.test(month)) || o.test(day))) || !(+month) || !(+day)) return false; | |
month = month.replace(o, ''); | |
if (month === '2') return isLeap ? day < 30 : day < 29; | |
return big.indexOf(month) === -1 ? day < 31 : day < 32; | |
} | |
return taste[2] === taste[4] && vaildDate(year, month, day); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
改了一下正则:
像最后一个
2012.04.32
这样的错误可以直接监测出来,return null
。不过
2.30
就需要额外的判断。