Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a Temporal PlainDateTime?

Is it possible to format a Temporal.PlainDateTime yet?

const f = new Intl.DateTimeFormat("en-us", {
    hour: "2-digit",
    minute: "2-digit",
})
const t = Temporal.Now.plainDateTimeISO().add({ 'nanoseconds': 10000000 })
const str = f.format(t)
like image 864
BAR Avatar asked Sep 24 '26 07:09

BAR


1 Answers

The easiest way to format a Temporal object is to use its toLocaleString() method. Here's an example of output using the latest Firefox nightly builds:

pdt = Temporal.Now.plainDateTimeISO().add({ 'nanoseconds': 10000000 });
pdt.toLocaleString("en-us", {
    hour: "2-digit",
    minute: "2-digit",
})
// => "01:15 PM"

If you're formatting many such objects, then it's faster to create the formatter once and re-use it, as you did in your OP sample.

dtf = new Intl.DateTimeFormat("en-us", {
    hour: "2-digit",
    minute: "2-digit",
})
pdt = Temporal.Now.plainDateTimeISO().add({ 'nanoseconds': 10000000 })
dtf.format(t)
// => "01:15 PM"

As @Jim noted above, you'll need a polyfill to use Temporal at this time (March 2025), because native implementations in browsers and Node are still in-progress.

like image 143
Justin Grant Avatar answered Sep 26 '26 20:09

Justin Grant