format a date in to the format october 13, 2014 11:13:00.000 am in typescript

You can use the moment.js library to format the date in the required format. Here's the sample code:

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

const date = new Date();
const formattedDate = moment(date).format('MMMM D, YYYY h:mm:ss.SSS A');
console.log(formattedDate); // October 13, 2014 11:13:00.000 AM
197 chars
6 lines

First, we import the moment.js library. Then we create a new Date object with the current date and time. We pass this object to the moment() function to create a moment object which provides a number of utilities to format and manipulate dates.

Finally, we use the format() method of the moment object to format the date in the required format.

The format string "MMMM D, YYYY h:mm:ss.SSS A" specifies the format of the resulting string where:

  • MMMM represents full month name (October)
  • D represents day of the month (13)
  • YYYY represents the full year (2014)
  • h represents the hour in 12-hour clock (11)
  • mm represents the minutes (13)
  • ss represents the seconds (00)
  • SSS represents the milliseconds (000)
  • A represents AM/PM marker (AM)

Hope this helps!

gistlibby LogSnag