format a date in to the format month day, year in typescript

To format a date in typescript, you could use the moment.js library. First, install moment.js in your project by running npm install moment.

Then import moment in your typescript file:

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

To format your date, pass your date to moment() and then use the format() function with the desired format:

index.ts
const date = new Date("2021-01-01");
const formattedDate = moment(date).format("MMMM D, YYYY");
console.log(formattedDate); // Output: "January 1, 2021"
153 chars
4 lines

In the example above, the format string "MMMM D, YYYY" means:

  • MMMM: full month name
  • D: day of month without leading zeros
  • YYYY: 4-digit year

You can modify the format string to get different date formats.

Note that moment.js provides many other functions to manipulate and format dates, so you can explore the library further if you need more advanced date handling.

gistlibby LogSnag