Last active
December 31, 2015 02:19
-
-
Save sorensen/7920006 to your computer and use it in GitHub Desktop.
date format
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
var val = someUserInput | |
// Check to see if a valid timestamp was used | |
if (!isNaN(+val)) { | |
if (val.length === 13 || val.length === 10) { | |
return new Date(val.length === 10 ? +val * 1000 : +val); | |
} | |
} | |
// Check if the string could be parsed by the date formatter | |
var parsed = dateFormat(val); | |
if (parsed) { | |
return new Date(parsed); | |
} | |
// Check if the string could be parsed as a Date object | |
var parsed = Date.parse(val); | |
if (!isNaN(parsed)) { | |
return new Date(parsed); | |
} |
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 dateFromString(str) { | |
var rx = /[0-9]{2,4}[\/-][0-9]{2}[\/-][0-9]{2,4}(\s?[0-9]{2}:[0-9]{2}(:[0-9]{2})?(\s?[a-zA-Z]{3})?)?/ | |
, defaults = [null, ' 00:00', ':00', ' UTC'] | |
, match = str.match(rx) | |
; | |
if (!match) { | |
return false; | |
} | |
for (var i = 1; i < match.length; i++) { | |
if (!match[i]) { | |
match[i] = defaults[i] | |
match[0] += defaults[i] | |
} | |
} | |
return match[0] | |
} |
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
var assert = require('assert') | |
;['02-20-2012' | |
, '2012-02-20 00:00' | |
, '02-20-2012 00:00' | |
, '02-20-2012 00:00:00' | |
, '02-20-2012 00:00:00 UTC' | |
].forEach(function(x) { | |
var str = dateFromString(x) | |
assert.strictEquals(1329696000000, +new Date(str), 'Mismatch for: ' + x) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment