format a date in to the format 'yyyy-mm-dd hh:mm:ss' in javascript

To format a date in JavaScript to the format 'yyyy-mm-dd hh:mm:ss', we can use the toISOString() method of the Date object and modify the resulting string using string manipulation. Here's an example code snippet:

index.tsx
const date = new Date();
const formattedDate = date.toISOString().replace('T', ' ').substring(0, 19);
console.log(formattedDate);
130 chars
4 lines

In this example, the Date object is created with the current date and time. We then call the toISOString() method on this object to get an ISO 8601 string representation of the date.

Since the toISOString() method returns a string in the format 'yyyy-mm-ddThh:mm:ss.sssZ', we need to modify it for our desired format. We do this by replacing the 'T' character with a space and then substringing the resulting string up to the 19th character, which gives us the 'yyyy-mm-dd hh:mm:ss' format.

The above code will output a string representing the current date and time in the format 'yyyy-mm-dd hh:mm:ss'.

gistlibby LogSnag