Javascript dates are frequently stored in UTC, or Coordinated Universal Time, specifically so we don’t have to store time-zone-adjusted dates. You’ll often see ISO-formatted date strings ending in Z
like this: 2022-12-15T21:07:49.883Z
. That Z means “Zulu”, and is just military jargon for “UTC”. Greenwich Mean Time (GMT) is also exactly the same: GMT === UTC === Zulu
.
Option 1: Use date.toLocaleString
Lets change that UTC to something more useful, since most internet users are not on UTC:
// Take a date string
const dateString = "2022-12-15T21:07:49.883Z";
// Turn it into a Date object
const dateObject = new Date(dateString);
// Thu Dec 15 2022 16:07:49 GMT-0500 (Eastern Standard Time)
// My browser automatically adjusted the format to EST, my location
dateObject.toLocaleString('en-US', { timeZone: "Asia/Shanghai" });
// '12/16/2022, 5:07:49 AM'
dateObject.toLocaleString('en-US', { timeZone: "Asia/Kolkata" });
// '12/16/2022, 2:37:49 AM'
dateObject.toLocaleString('en-US', { timeZone: "America/Los_Angeles" });
// '12/15/2022, 1:07:49 PM'
// Using locales, you can also get the correct date format
// for the date's location if needed
dateObject.toLocaleString("en-IN", { timeZone: "Asia/Kolkata" })
// '16/12/2022, 2:37:49 am'
dateObject.toLocaleString('zh-cn', { timeZone: "Asia/Shanghai" });
// '2022/12/16 05:07:49'
Option 2: Use Intl.DateTimeFormat
If you’re going to do a lot of converting to a specific time zone or locale, you can also use the Intl.DateTimeFormat built-in:
// this californiaTime object will have a .format() method
// which operates on Date() objects
const californiaTime = new Intl.DateTimeFormat(
"en-US",
{
timeZone: "America/Los_Angeles",
timeStyle: "long",
dateStyle: "short",
}
);
const randomIsoTimes = [
"2022-01-03T22:21:54Z",
"2012-12-15T21:31:38Z",
"1999-06-01T04:04:28Z",
]
// Now pass each of these dates to our pre-built formatter
randomIsoTimes.map(timeString =>
californiaTime.format(new Date(timeString))
)
/*
[
'1/3/22, 2:21:54 PM PST',
'12/15/12, 1:31:38 PM PST',
'5/31/99, 9:04:28 PM PDT',
]
*/
Personally, I find the Intl package to be a bit much for most use cases and I usually use .toLocaleString()
, but Intl does have a ton of options for customization. Intl is also very useful for reformatting numbers, particularly currencies, but that’ll be for another post.
Helpful Links
- What is UTC or GMT time? – noaa.gov
- Wikipedia List of tz database timezones, like
Asia/Shanghai