Skip to content

Instantly share code, notes, and snippets.

@Matsukii
Last active December 4, 2020 23:09
Show Gist options
  • Select an option

  • Save Matsukii/55b1cb22dc0af599645826a25189dc82 to your computer and use it in GitHub Desktop.

Select an option

Save Matsukii/55b1cb22dc0af599645826a25189dc82 to your computer and use it in GitHub Desktop.
build a date from string with format; example: buildDate('%mo%/%d% %h%:%min%') -> 'Dec/4 20:00'
/**
* @description date builder, build a date string by passing the format
* @param {String} format date format to create
* @param {Number} timestamp date timestamp
* @see https://jsbench.me/j6kiav1wop other versions and benchmark
* @example buildDate('%mo%/%d% %h%:%min%') -> 'Dec/4 20:00'
*/
buildDate = (format = '*', timestamp = Date.now()) => {
if(!format || format == "*" || format == " "){
return new Date(timestamp);
}
let d = new Date(timestamp)
let replacers={
'%m%': () => d.getMonth()+1,
'%y4%': () => d.getFullYear(),
'%ms%': () => d.getMilliseconds(),
'%d%': () => d.getDate(),
'%h%': () => d.getHours(),
'%min%':() => d.getMinutes(),
'%mo%': () => d.toDateString().substr(4,3),
'%day%':() => d.toDateString().substr(0,3),
'%mm%': () => `${d.getMonth()+1}`.padStart(0, 2),
'%dd%': () => `${d.getDate()}`.padStart(0, 2),
}
let replacable = Object.keys(replacers);
let toReplace = format.match(/%[a-z0-9]{1,}%/gi)
for (let i = 0; i<toReplace.length; i++){
if(replacable.includes(toReplace[i])){
format = format.replace(toReplace[i], replacers[toReplace[i]]())
}
}
return format
}
buildDate('%y4%-%mo%')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment