Skip to content

Instantly share code, notes, and snippets.

@gitbuh
Created April 22, 2012 22:23
Show Gist options
  • Save gitbuh/2467296 to your computer and use it in GitHub Desktop.
Save gitbuh/2467296 to your computer and use it in GitHub Desktop.
Normalize date string
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