format a date in to the format month day, year hour:minute:second.fff am/pm in javascript

Here's an example code snippet to format date in the required format:

const date = new Date();
const formattedDate = new Intl.DateTimeFormat('default', {
  year: 'numeric',
  month: 'short',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: true,
  fractionalSecondDigits: 3
}).format(date);

console.log(formattedDate);
290 chars
14 lines

The output will be something like Aug 10, 2022 8:13:45.789 PM based on the current date and time.

Intl.DateTimeFormat is a built-in API in JavaScript that allows internationalized formatting of dates and times. The options passed to the DateTimeFormat constructor specify the required format.

  • year, month and day are set to numeric and short to format the date as month day, year
  • hour, minute, and second are set to numeric to format the time as hour:minute:second
  • hour12 is set to true to display the time in AM/PM format
  • fractionalSecondDigits is set to 3 to display milliseconds with 3 digits.

gistlibby LogSnag