Skip to content

Instantly share code, notes, and snippets.

@vasanthv
Last active October 22, 2022 02:26
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 vasanthv/de2d57e3fd00b1bfdff1efb0cdbc0adb to your computer and use it in GitHub Desktop.
Save vasanthv/de2d57e3fd00b1bfdff1efb0cdbc0adb to your computer and use it in GitHub Desktop.
Format a date string
/*
This function changes the datestring to the following format
Jan 29 2018 - 09:51 AM
*/
function formatDate(dateString){
const date = new Date(dateString);
const hours = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
return [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ][date.getMonth()] + ' '
+ (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
+ date.getFullYear() + ' - '
+ (hours < 10 ? '0' + hours : hours) + ':'
+ (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ' '
+ (date.getHours() >= 12 ? 'PM' : 'AM');
}
console.log(formatDate('2018-01-29 16:21:39.901Z'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment