iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📆
Flexible Date and Time Formatting with formatToParts and Object.fromEntries
If you want to format dates, you can use Intl.DateTimeFormat in modern browsers.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
There are various settings for locale and options, so most things are possible.
For example, a notation like "Month x, Day y" would look like this:
new Intl.DateTimeFormat("ja-JP",{month:"long", day:"numeric" })
.format(new Date())
// => 10月20日
However, you might not remember which option does what, or you might want more flexible formatting.
Extracting from formatToParts
By using formatToParts, you can receive the result as an array of parts for each component.
new Intl.DateTimeFormat("ja-JP")
.formatToParts(new Date())
[
{"type": "year","value": "2022"},
{"type": "literal", "value": "/"},
{"type": "month", "value": "10"},
{"type": "literal", "value": "/"},
{"type": "day", "value": "20"}
]
But in this state, it's a bit difficult to handle for formatting.
Making it easier to handle with Object.fromEntries
Combining this with Object.fromEntries allows you to handle it as an object, making it much easier to work with.
const getFormatParts = (date: Date) => {
return Object.fromEntries(
new Intl.DateTimeFormat("ja-JP", {dateStyle:"full", timeStyle:"full"})
.formatToParts(date)
.map(({type, value}) => [type,value])
)
}
{
"year": "2022",
"literal": "秒 ",
"month": "10",
"day": "20",
"weekday": "木曜日",
"hour": "20",
"minute": "58",
"second": "24",
"timeZoneName": "日本標準時"
}
After that, you can use it like this:
const dateParts = getFormatParts(new Date())
const formatted = `${dateParts.month}月${dateParts.day}日 [${dateParts.weekday}]`
// => '10月20日(木曜日)'
Discussion