Created
November 11, 2014 17:20
-
-
Save psema4/401cc0ba87017ee0e22c to your computer and use it in GitHub Desktop.
Convert non-relative date.js-like string to a js Date object
This file contains hidden or 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
// see also https://github.com/MatthewMueller/date/issues/57 | |
// usage: var someDateObj = DateGenerator("Jan 3 at 4 pm").dt; | |
function DateGenerator(str) { | |
function lookupMonth(str) { | |
var monthsFull = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], | |
monthsShort = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], | |
result = -1 | |
; | |
result = (monthsFull.indexOf(str) > -1) | |
? monthsFull.indexOf(str) | |
: (monthsShort.indexOf(str) > -1) | |
? monthsShort.indexOf(str) | |
: -1 | |
; | |
if (result >= 0) result++; // make 1-based index (human) | |
return result; | |
} | |
function generateFromString(str) { | |
var parts = str.split(' '), | |
// extract string parts: | |
// expects a string with structure "MMM DD at HH [am|pm]" | |
// ie. "Jan 1 at 3 pm" | |
month = parts[0], | |
d = parts[1], | |
at = parts[2], //fixme: detect (optional) year | |
hour = parseInt(parts[3], 10), | |
ampm = parts[4], | |
_date = new Date(), // today | |
yyyy = _date.getFullYear(), | |
_mm = _date.getMonth() + 1, | |
mm = lookupMonth(month), | |
date1, | |
date2, | |
hourOffset | |
; | |
//fixme: if requested month is less than current month, assume next year. | |
if (mm < _mm) { | |
yyyy++; | |
} | |
date1 = new Date(yyyy + '-' + mm + '-' + d + ' 00:00:00'); // 12:00am on specified date | |
if (ampm.toLowerCase() == 'am' && hour == 12) hour = 0; | |
if (ampm.toLowerCase() == 'pm' && hour < 12) hour += 12; | |
hourOffset = ((60000*60) * hour); | |
date2 = new Date(date1.valueOf() + hourOffset); | |
return date2; | |
} | |
var dt = new Date(); | |
if (str) { | |
dt = generateFromString(str); | |
} | |
return { | |
str: str, | |
dt: dt, | |
lookupMonth: lookupMonth, | |
generateFromString: generateFromString | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment