How to format Milliseconds with Intl.DateTimeFormat API
Asked Answered
T

1

11

I need to format a Timestamp in a specific locale (not utc, not browser locale). But I must have the millisecond part of the date, too. My first attempt was second:'numeric' with the DateTimeFormat API:

new Intl.DateTimeFormat(
    'de-de', // german as an example, user selectable
    { 
        year: 'numeric', month: 'numeric',  day: 'numeric', 
        hour: 'numeric', minute: 'numeric', 
        second: 'numeric',
        hour12: false
    }
)
.format(new Date()); // Date as an example

But the result is something like "26.11.2018, 09:31:04" and not "26.11.2018, 09:31:04,243".

Is there a easier possibility than using formatToParts() and detect the missing millisecond and add it again with the Intl.NumberFormat?

Attention: If someone needs to implement this, Microsoft browsers are adding Left-To-Right-Mark Unicode chars into the output. So you can not parseInt the result from formatToParts() without sanitizing.

Edit: Moved the question to https://github.com/tc39/ecma402/issues/300

Tamica answered 26/11, 2018 at 8:45 Comment(1)
Yup, there doesn't seem to be a clean answer to this. Since seconds are completely immune from timezone issues, I would remove seconds from your formatting object, and concatenate them with a call to myDate.getSeconds().Longe
T
8

This is now spec'ed and implemented in Chrome and Firefox:

https://github.com/tc39/ecma402/issues/300

https://caniuse.com/mdn-javascript_builtins_intl_datetimeformat_datetimeformat_options_parameter_options_fractionalseconddigits_parameter

new Date().toLocaleString('de-de', { year: 'numeric', month: 'numeric',  day: 'numeric', 
        hour: 'numeric', minute: 'numeric', 
        second: 'numeric',
        fractionalSecondDigits: 3
    }
)
// or
new Intl.DateTimeFormat(
    'de-de', // german as an example, user selectable
    { 
        year: 'numeric', month: 'numeric',  day: 'numeric', 
        hour: 'numeric', minute: 'numeric', 
        second: 'numeric', fractionalSecondDigits: 3,
        hour12: false
    }
)
.format(new Date());
// => "6.1.2021, 12:30:52,719"
Tamica answered 6/1, 2021 at 11:32 Comment(1)
Somehow I was always getting one more second when subtracting timestamp of two dates to get offset difference and then init new date based on that. After researching at many places, finally found this answer.Hyades

© 2022 - 2024 — McMap. All rights reserved.