Skip to content

Instantly share code, notes, and snippets.

@sofish
Created October 10, 2012 12:25
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofish/3865287 to your computer and use it in GitHub Desktop.
Save sofish/3865287 to your computer and use it in GitHub Desktop.
detect date type
// 仅支持 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);
}
@chrisyip
Copy link

改了一下正则:

re = /\b(\d{4})[-\/\.]?(1[0-2]|0?[1-9])[-\/\.]?([1-2]\d|3[01]|0?[1-9])\b/;
console.log('2012-4-21'.match(re));
console.log('2012-2-29'.match(re));
console.log('2012-2-30'.match(re));
console.log('2012130'.match(re));
console.log('201213'.match(re));
console.log('2012/4/21'.match(re));
console.log('2012/04/21'.match(re));
console.log('2012.04.21'.match(re));
console.log('2012.04.32'.match(re));

像最后一个 2012.04.32 这样的错误可以直接监测出来,return null
不过 2.30 就需要额外的判断。

@chrisyip
Copy link

同时也能把 2012130 识别为 2012-1-302012123 识别为 2012-12-3
2012132 -> null
20121232 -> null

@sofish
Copy link
Author

sofish commented Oct 11, 2012

@chrisyip 非常赞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment