postgres convert date to string in javascript

To convert a date from Postgres to a string in JavaScript, you can use the toLocaleString() function, which is available on the Date object in JavaScript:

index.tsx
// Example date from Postgres
var pgDate = new Date('2022-02-22T03:24:00.000Z');

// Convert date to string
var dateString = pgDate.toLocaleString(); // "2/22/2022, 3:24:00 AM" (default locale format)

// Specifying custom date format
var options = { year: 'numeric', month: 'long', day: 'numeric' };
var dateString2 = pgDate.toLocaleString('en-US', options); // "February 22, 2022"
383 chars
10 lines

In the above example, we create a new Date object with a string representation of the date from Postgres. Then, we use the toLocaleString() function to format the date as a string. By default, toLocaleString() will use the current user's locale settings to format the date. However, you can also specify custom options to format the date in a specific way.

gistlibby LogSnag