Skip to content

Instantly share code, notes, and snippets.

@ericdmoore
Last active April 8, 2021 18:39
Show Gist options
  • Save ericdmoore/29a4c9cd99aed96fde1d6a19fff137f3 to your computer and use it in GitHub Desktop.
Save ericdmoore/29a4c9cd99aed96fde1d6a19fff137f3 to your computer and use it in GitHub Desktop.
Date Formatter Fn
/**
* ### Date Formatter
* @description Given a format string, the formatter does simple replacment for date string tokens.
* @param epoch - ISO Epoch Date number
* @param fmt - format String
*
* @token `YYYY`:Year; ex: 2021
* @token `YY`:AbbrevYear; 21
* @token `MM`:Month; 04
* @token `DD`:Date; 01
* @token `HH`:24 Hours; 13
* @token `%H`:Am/pm Hours; 01
* @token `hh`:Am/pm Hours; 01pm
* @token `mm`:minutes; 59
* @token `ss`:seconds; 42
* @example
* ```js
* fmtDate('YYYYMMDDhhmmmsss')(Date.now()) // '2021040801pm27m59s'
* ```
*/
export const fmtDate = (fmt:string = 'YYYYMMDDHH')=>{
const p2 = (s:string)=>s.padStart(2, '0')
return (epoch:number) => {
const d = new Date(epoch)
const YYYY = d.getFullYear().toString()
const YY = p2(d.getFullYear().toString().slice(-2))
const MM = p2((d.getMonth()+1).toString())
const DD = p2(d.getDate().toString())
const HH = p2(d.getHours().toString())
const mm = p2(d.getMinutes().toString())
const ss = p2(d.getSeconds().toString())
const H = p2((d.getHours() % 12).toString())
const ampm = d.getHours() > 11 ? 'pm' : 'am'
const hh = `${H}${ampm}`
return fmt
.replace('YYYY',YYYY)
.replace('ampm',ampm)
.replace('YY',YY)
.replace('MM',MM)
.replace('DD',DD)
.replace('HH',HH)
.replace('%H',H)
.replace('mm',mm)
.replace('ss',ss)
.replace('hh',hh)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment