Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Last active December 22, 2024 21:56
Show Gist options
  • Save allenhwkim/69bde26dd6b4d580c3ae62f9bd7d6244 to your computer and use it in GitHub Desktop.
Save allenhwkim/69bde26dd6b4d580c3ae62f9bd7d6244 to your computer and use it in GitHub Desktop.
Simple date format function
// yyyy - full uyear, e.g. 1969
// mm - two digit month, e.g. 01, 12
// mmm - e.g. Jan, Feb, Mar
// dd - two digit date e.g. 01, 31
// ddd - 1st, 2nd 21st
// www - e.g. Mon, Tue, Wed...
function formatDate(date, format = 'yyyy-mm-dd') { // mm/dd/yyyy, www MMM DDD YYYY
const day = date.getDate();
const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const daySuffix =
day > 3 && day < 21 ? 'th' :
day % 10 === 1 ? 'st':
day % 10 === 2 ? 'nd':
day % 10 === 3 ? 'rd': 'th';
const yyyy = date.getFullYear()
const mmm = months[date.getMonth()];
const mm = ('0' + (date.getMonth() + 1)).slice(-2)
const dd = ('0' + day).slice(-2);
const ddd = day + daySuffix;
const www = weekdays[date.getDay()];
return format
.replace('www', www).replace('www', www)
.replace('yyyy', yyyy).replace('YYYY', yyyy)
.replace('mmm', mmm).replace('MMM', mmm)
.replace('mm', mm).replace('MM', mm)
.replace('ddd', ddd).replace('DDD', ddd)
.replace('dd', dd).replace('DD', dd)
}
formatDate(new Date(), 'yyyy-mm-dd');
formatDate(new Date(), 'mm/dd/yyyy');
formatDate(new Date(), 'www mmm ddd yyyy');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment