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

One way to format a date in JavaScript to the format "month day, year" is to use the toLocaleDateString() method, with the desired format options.

Here's an example:

index.tsx
const date = new Date();
const options = { month: 'long', day: 'numeric', year: 'numeric' };
const formattedDate = date.toLocaleDateString('en-US', options);

console.log(formattedDate); // prints something like "April 23, 2022"
229 chars
6 lines

In this example, we create a new Date object representing the current date and time. We then define an object options with the desired formatting options - in this case, we want the full name of the month, the numeric day of the month, and the full year.

Finally, we call the toLocaleDateString() method on the date object, passing in the desired locale ('en-US' in this case) and the options object. The result is a formatted date string in the desired format.

gistlibby LogSnag