Created
December 15, 2016 07:16
-
-
Save zafergurel/e33658ddd46f4d4e45c8c03e4f13b05e to your computer and use it in GitHub Desktop.
String.convertToDate.js is a small extension method for the javascript String class. It's used to convert a string to a Date object by specifying a format string.
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
/* | |
The following code extends String class so that you can use convertToDate on a string object. | |
format can be a combination of "yy" or "yyyy" for year, "mm" for month and "dd" for day. | |
format is case-insensitive. | |
The seperator between date part markers may be "/", "." or "-". | |
Some examples: | |
"2016-12-31".convertToDate("yy-mm-dd") (same as "2016-12-31".convertToDate("yyyy-mm-dd")) | |
"31.12.2016".convertToDate("dd.MM.yyyy") | |
"12/31/2016".convertToDate("MM/dd/yyyy") | |
*/ | |
String.prototype.convertToDate = function (format) { | |
var formatParts = format.toLowerCase().split(/[/.-]/); | |
var dateParts = this.split(/[/.-]/); | |
var yearIndex, monthIndex, dayIndex; | |
for(var i=0; i < formatParts.length; i++) { | |
if(formatParts[i] === "dd") dayIndex = i; | |
if(formatParts[i] === "mm") monthIndex = i; | |
if(formatParts[i] === "yy" || formatParts[i] === "yyyy") yearIndex = i; | |
} | |
return new Date(Number(dateParts[yearIndex]), Number(dateParts[monthIndex]) - 1, Number(dateParts[dayIndex])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment