Date value vs. Date Label
• ⏱︎ 2 min read
When you use new Date()
with an ISO 8601
date string, which is a way of saying YYYY-MM-DD
, JavaScript parses the date string in the UTC
timezone.
💭 Think of this as the date value
.
const date = new Date('2024-02-13')
console.log(date.toISOString()); // '2024-02-13T00:00:00.000Z'
Displaying Dates in the Browser
A good semantic way to display a date would be:
<time datetime={date.toISOString()}>
{
date.toLocaleDateString("en-us", {
year: "numeric",
month: "short",
day: "numeric",
})
}
</time>
💭 Think of this as the date label
.
However, since the toLocaleDateString()
method displays the date in the user’s local time zone,
this may not match the UTC date
<time datetime="2024-02-13T00:00:00.000Z"> Feb 12, 2024 </time>
Date value vs. Date label
- date value: is the internal, representation of the date (in UTC)
- date label: is the localized presentation of that date
To control the output or date label
we can specify the timezone parameter.
// Users in America/New_York
date.toLocaleDateString("en-us", {
year: "numeric",
month: "short",
day: "numeric",
timeZone: 'America/New_York'
}) // Might output: "Feb 12, 2024", depending on DST
// Users in Tokyo
date.toLocaleDateString("en-us", {
year: "numeric",
month: "short",
day: "numeric",
timeZone: 'Asia/Tokyo'
})); // Outputs: "Feb 13, 2024"
// Same as the date value
date.toLocaleDateString("en-us", {
year: "numeric",
month: "short",
day: "numeric",
timeZone: 'UTC'
}) // => Feb 13, 2024
👋 But in Production…
- You should use something that has covered a lot of edge cases like: @internationalized/date