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

You can format a date in the desired format in JavaScript using the toLocaleDateString() and toLocaleTimeString() methods.

Here's an example code snippet that formats a Date object in the format "month day, year hour:minute am/pm":

index.tsx
const date = new Date();
const formattedDate = `${date.toLocaleString('en-US', { month: 'long', day: 'numeric' })}, ${date.getFullYear()} ${date.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })}`;

console.log(formattedDate); // e.g. "August 23, 2021 10:15 AM"
290 chars
5 lines

In this example, we first create a new Date object with the current date and time. Then, we use toLocaleString() with appropriate options to format the date and time parts into the desired format. Finally, we concatenate the formatted parts into a single string.

Note that the en-US locale is used here for formatting, which may not be appropriate for all use cases. You may need to adjust the locale or other formatting options depending on your requirements.

related categories

gistlibby LogSnag