Skip to content

Instantly share code, notes, and snippets.

@JackHowa
Created November 27, 2020 16:09
Show Gist options
  • Save JackHowa/9806ecf7063816411bff42d3dfe27b07 to your computer and use it in GitHub Desktop.
Save JackHowa/9806ecf7063816411bff42d3dfe27b07 to your computer and use it in GitHub Desktop.
format date
const MONTH_NAMES = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
// input date object
// July 15, 2020 at 1:30PM EST
function formatDate(dateObject) {
const monthNumber = dateObject.getMonth();
const month = MONTH_NAMES[monthNumber];
const dayDate = dateObject.getDate();
const fullYear = dateObject.getFullYear();
const localHours = dateObject.getHours();
const localMinutes = `${(dateObject.getMinutes() < 10 ? '0' : '')}${dateObject.getMinutes()}`;
const localTime = `${localHours % 12 || 12}:${localMinutes}${localHours >= 12 ? 'PM' : 'AM'}`;
// get local timezone abbreviation
// String(String(rightNow).split("(")[1]).split(")")[0])
// somewhat less reliable for other timezones
// via https://stackoverflow.com/questions/1954397/detect-timezone-abbreviation-using-javascript
const timezoneAbbreviation = dateObject.toLocaleTimeString(undefined, { timeZoneName: 'short' }).split(' ')[2];
return `${month} ${dayDate}, ${fullYear} at ${localTime} ${timezoneAbbreviation}`;
}
export default formatDate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment