I get data from a database as an ISO-8601 date time string in UTC and then I need to convert it to a local date string in the format YYYY-MM-DD.
This code works but I'm wondering if there's a better way to do it...
const zeroPad = n => n < 10 ? '0' + n : n
const d = new Date('2021-07-06T01:00:00.000Z') // UTC 1 AM
const month = zeroPad(d() + 1)
const date = zeroPad(d())
const result = `${d.getFullYear()}-${month}-${date}`
console.log(result); // US/Eastern 8 PM - date is 1 day earlier
It feels a bit unwieldy but am trying to avoid the overhead of external libraries.
Any thoughts?
You can try toLocaleDateString as the format you're after is given by language en-CA (and maybe others):
console.log(
new Date('2021-07-06T01:00:00.000Z').toLocaleDateString('en-CA')
);
The caveat with any toLocale* method is that you aren't guaranteed that all implementations will return the same format and may fallback to some implementation dependent format. So don't use it if that matters.