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

To format a date in the specified format, we can make use of the Moment.js library.

First, we need to install Moment.js using the following command:

npm install moment
19 chars
2 lines

Then, we can import it in our Typescript file as follows:

index.ts
import * as moment from 'moment';
34 chars
2 lines

Now, we can create a Date object and pass it to moment to format it:

index.ts
const date = new Date();
const formattedDate = moment(date).format('MMMM D, YYYY h:mm a');
console.log(formattedDate); // e.g. January 1, 2022 3:45 pm
151 chars
4 lines

In the above code, we are creating a Date object, and then passing it to moment. We are using the format function to specify the desired format for the output string.

The format string we're specifying is: MMMM D, YYYY h:mm a

Here's what each part of the format string means:

  • MMMM: full month name
  • D: day of the month
  • YYYY: four-digit year
  • h: hour (12-hour clock)
  • mm: minutes
  • a: lowercase am/pm

The resulting string is then printed to the console.

gistlibby LogSnag