Skip to content

Instantly share code, notes, and snippets.

@luofei2011

luofei2011/check date

Last active Aug 29, 2015
Embed
What would you like to do?
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