Skip to content

Instantly share code, notes, and snippets.

@superjojo140
Last active March 10, 2021 12:47
Show Gist options
  • Save superjojo140/1da78945b2f2ccc8493fdaf001fa8e42 to your computer and use it in GitHub Desktop.
Save superjojo140/1da78945b2f2ccc8493fdaf001fa8e42 to your computer and use it in GitHub Desktop.
Format javascript Date object with template string
/**
* Formats a date as string specified by a template string
* @param date Date to be formatted
* @param templateString Template of the expected format. e.g. "YYYY-MM-DD hh:mm:ss" or "YY-M-D h:m:s" to trim leading zeros
*/
export function formatDate(date: Date, templateString: string): string {
const year = date.getFullYear().toString();
const shortYear = date.getFullYear().toString().substr(2, 2);
const month = date.getMonth() < 9 ? "0" + String(date.getMonth() + 1) : String(date.getMonth() + 1);
const shortMonth = String(date.getMonth() + 1);
const day = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
const shortDay = date.getDate().toString();
const hours = date.getHours() < 10 ? "0" + date.getHours().toString() : date.getHours().toString();
const shortHours = date.getHours().toString();
const minutes = date.getMinutes() < 10 ? "0" + date.getMinutes().toString() : date.getMinutes().toString();
const shortMinutes = date.getMinutes().toString();
const seconds = date.getSeconds() < 10 ? "0" + date.getSeconds().toString() : date.getSeconds().toString();
const shortSeconds = date.getSeconds().toString();
return templateString
.replace('YYYY', year)
.replace('YY', shortYear)
.replace('MM', month)
.replace('M', shortMonth)
.replace('DD', day)
.replace('D', shortDay)
.replace('hh', hours)
.replace('h', shortHours)
.replace('mm', minutes)
.replace('m', shortMinutes)
.replace('ss', seconds)
.replace('s', shortSeconds)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment