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

You can use Moment.js library to format the date into the desired format. First, install Moment.js using npm:

npm install moment --save

Then import and use the format() method to format the date:

index.ts
import * as moment from 'moment';

const date = new Date();
const formattedDate = moment(date).format('MMMM DD, YYYY hh:mm:ss.SSS A z');
console.log(formattedDate); // e.g. "November 07, 2021 10:35:30.000 PM UTC"
213 chars
6 lines

Explanation of the format string used:

  • MMMM: full month name
  • DD: day of the month (with leading zero if less than 10)
  • YYYY: full year
  • hh: hour in 12-hour format (with leading zero if less than 10)
  • mm: minute (with leading zero if less than 10)
  • ss: second (with leading zero if less than 10)
  • SSS: milliseconds (with leading zeroes if less than 100)
  • A: AM or PM
  • z: time zone abbreviation (e.g. UTC, EST, etc.)

gistlibby LogSnag