Skip to content

Instantly share code, notes, and snippets.

@luofei2011
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luofei2011/66798cb6207d1e7c30b3 to your computer and use it in GitHub Desktop.
Save luofei2011/66798cb6207d1e7c30b3 to your computer and use it in GitHub Desktop.
is the correct date string
/**
* @description 判断是否为合法的日期字符串
* @param {String} str 目标字符串
* @return {Boolean} 是否是合法的
*/
function check(str) {
var obj = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
};
var match = str.match(/(\d{4})-(\d{2})-(\d{2})/);
return match && match[0] && match[1] >= 2010 && match[1] <= 2099 && match[2] <= 12 && (match[3] <= obj[+match[2]]);
}
// test
check('2015-06-02'); // true
check('2015-02-31'); // false
/**
* @description 单纯的判断是否是正确的日期
* @param {Any} v 任何类型的值
* @return {Boolean} 是否能得到正确的日期
*/
function isDate(v) {
return (+new Date(v)).toString() !== 'NaN';
}
// test
isDate('2015-12-12'); // true
isDate('abc'); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment