Created
June 2, 2010 07:16
-
-
Save cms/422052 to your computer and use it in GitHub Desktop.
parseDate
This file contains 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
function parseDate(str, format) { | |
format = format || 'yyyy-mm-dd'; // default format | |
// build a regular expression to match the format | |
var i = 0, fmt = {}, | |
re = new RegExp('^'+format.replace(/(yyyy|dd|mm)/g, function (match) { | |
fmt[match] = ++i; // store format position | |
return '(\\d{'+match.length+'})'; // make a capturing group | |
})+'$'), parts = str.match(re); // match the date parts | |
if (!parts) return null; // input didn't match the format pattern | |
return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']] || 1); | |
} | |
console.log(parseDate('06-01-2010', 'mm-dd-yyyy')); | |
console.log(parseDate('01.06.2010', 'dd.mm.yyyy')); | |
console.log(parseDate('06-01-2010', 'mm-dd-yyyy')); | |
console.log(parseDate('01-06-2010', 'dd-mm-yyyy')); | |
console.log(parseDate('01/06/2010', 'dd/mm/yyyy')); | |
console.log(parseDate('06/01/2010', 'mm/dd/yyyy')); | |
console.log(parseDate('2010-06', 'yyyy-mm')); | |
console.log(parseDate('2010-06-01')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment