Skip to content

Instantly share code, notes, and snippets.

@justin-schroeder
Last active January 20, 2020 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justin-schroeder/41505a6be88bfa25467e4ed5161608c2 to your computer and use it in GitHub Desktop.
Save justin-schroeder/41505a6be88bfa25467e4ed5161608c2 to your computer and use it in GitHub Desktop.
JavaScript moment-js style date formatting function
/**
* Given a date, return a format. I've always wanted a cheap way to do this
* without installing a full library.
*
* Credit: https://gist.github.com/justin-schroeder/41505a6be88bfa25467e4ed5161608c2
*
* @param {Date} date
* @return {string}
*/
export function format (date, format) {
// ----- Years -----
const yr = date.getFullYear()
let shortYr = yr % (Math.floor(yr / 100) * 100)
// ----- Hours -----
const hour = date.getHours()
const shortHour = hour === 0 ? 12 : (hour > 12 ? hour - 12 : hour)
shortYr = shortYr < 10 ? '0' + shortYr : '' + shortYr
// ----- Minutes -----
const minute = date.getMinutes()
// ----- Seconds -----
const second = date.getSeconds()
// ----- Months -----
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
// ----- Days -----
const dateOfMonth = date.getDate()
// ----- Ordinal -----
const ordinals = ['th', 'st', 'nd', 'rd'].concat(Array(10).fill('th'))
const replacements = {
YYYY: yr,
YY: shortYr,
HH: hour < 10 ? '0' + hour : '' + hour,
H: hour,
h: shortHour,
kk: hour + 1,
k: hour + 1 < 10 ? '0' + hour + 1 : hour + 1,
a: hour >= 12 ? 'pm' : 'am',
A: hour >= 12 ? 'PM' : 'AM',
mm: minute < 10 ? '0' + minute : minute,
m: minute,
ss: second < 10 ? '0' + second : second,
s: second,
MMMM: months[date.getMonth()],
MMM: months[date.getMonth()].substr(0, 3),
MM: (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1),
M: '' + date.getMonth(),
DD: dateOfMonth < 10 ? '0' + dateOfMonth : dateOfMonth,
D: dateOfMonth,
o: ordinals[dateOfMonth > 13 ? dateOfMonth % 10 : dateOfMonth]
}
return format.replace(/Y{2,4}|H{1,2}|h|k{1,2}|a|A|m{1,2}|s{1,2}|M{1,4}|D{1,2}|o/g, (match) => replacements[match])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment