Skip to content

Instantly share code, notes, and snippets.

@chefe
Created February 5, 2014 12:00
Show Gist options
  • Save chefe/8822231 to your computer and use it in GitHub Desktop.
Save chefe/8822231 to your computer and use it in GitHub Desktop.
Format a javascript date as a string, based on a format string
/**
* Format date as a string
* @param Date date a date object (usually "new Date();")
* @param string format a string format, eg. "DD-MM-YYYY"
*/
function dateFormat(date, format) {
// Calculate date parts and replace instances in format string accordingly
// Hint: Months are zero-based
// Date
format = format.replace("DD", leadingZeroInt(date.getDate()));
format = format.replace("D", date.getDate());
format = format.replace("MM", leadingZeroInt(date.getMonth() + 1));
format = format.replace("M", (date.getMonth() + 1));
format = format.replace("YYYY", date.getFullYear());
// Time
format = format.replace("hh", leadingZeroInt(date.getHours()));
format = format.replace("h", date.getHours());
format = format.replace("mm", leadingZeroInt(date.getMinutes()));
format = format.replace("m", date.getMinutes());
format = format.replace("ss", leadingZeroInt(date.getSeconds()));
format = format.replace("s", date.getSeconds());
// Return value
return (format.indexOf("NaN") != -1) ? date : format;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment