Created
January 30, 2017 11:02
-
-
Save Aymkdn/b17903cf7786578300f04f50460ebe96 to your computer and use it in GitHub Desktop.
Date.parseFrom() permits to parse a string to a JavaScript Date
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
/** | |
* Parse a string to a Date | |
* @param {String} strDate | |
* @param {String} format Supported format including YYYY, YY, MM, M, DD, D, with - and / separators | |
* @return {Date|Throw} the JS Date object, or throw Error("Invalid Date") if strDate is invalid | |
* @compatibility IE9+ | |
* @example | |
* Date.parseFrom("1/10/2017", "MM/DD/YYYY"); // -> new Date(2017,0,10) | |
*/ | |
Date.parseFrom=function(strDate, format) { | |
var year,month,day; | |
// find the separators | |
var separator=" "; | |
if (strDate.indexOf("-") > -1) separator="-"; | |
else if (strDate.indexOf("/") > -1) separator="/"; | |
strDate=strDate.split(separator); | |
format=format.split(separator); | |
format.forEach(function(d,i) { | |
switch(d.charAt(0)) { | |
case "Y": year=strDate[i]*1; break; | |
case "M": month=strDate[i]*1-1; break; | |
case "D": day=strDate[i]*1; break; | |
} | |
}); | |
if (year===undefined || month===undefined || day===undefined) throw Error('invalid date'); | |
return new Date(year,month,day); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment