Created
April 22, 2012 22:23
-
-
Save gitbuh/2467296 to your computer and use it in GitHub Desktop.
Normalize date string
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
function normalizeDate(dateString) { | |
// If it's not at least 6 characters long (8/8/88), give up. | |
if (dateString.length && dateString.length < 6) { | |
return ''; | |
} | |
var date = new Date(dateString), | |
month, day; | |
// If input format was in UTC time, adjust it to local. | |
if (date.getHours() || date.getMinutes()) { | |
date.setMinutes(date.getTimezoneOffset()); | |
} | |
month = date.getMonth() + 1; | |
day = date.getDate(); | |
// Return empty string for invalid dates | |
if (!day) { | |
return ''; | |
} | |
// Return the normalized string. | |
return date.getFullYear() + '-' + | |
(month > 9 ? '' : '0') + month + '-' + | |
(day > 9 ? '' : '0') + day; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment