Hey everyone| just checking if I am doing something wrong. The code below gives me time = 24:59, in Prague (GMT+1). Using Chrome.
new Intl.DateTimeFormat(
'en',
{
weekday: 'long',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: false
}
).format(new Date('2020-03-11T23:59:00Z')
)
// "Thursday, March 12, 24:59"
When using the .getHours() I will get a correct value of 0 though.
new Date('2020-03-11T23:59:00Z'); // Thu Mar 12 2020 00:59:00 GMT+0100 (Central European Standard Time)
new Date('2020-03-11T23:59:00Z').getHours(); // 0
Thanks for suggestions, I didn't found any related issues about this.
Tomas
The Intl.DateTimeFormat object enables language-sensitive date and time formatting. Creates a new Intl.DateTimeFormat object. Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
The downside of Intl.DateTimeFormat is that we can't fully control over the shape of the format itself. We can only depend on the formats which have been standardized by ECMA. Take a look at the previous example.
The only way to format date and time via native Javascript's API is by messing around with Date class. To start formatting, we need to provide a timestamp from API as a parameter to Date and then call its constructor function to instantiate the object.
Using DateTimeFormat In basic use without specifying a locale, DateTimeFormat uses the default locale and default options. var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); console.log(new Intl.DateTimeFormat().format(date));
Your code gives me "Thursday, March 12, 00:59"
in Firefox and "Thursday, March 12, 24:59"
in Chrome (80.0.3987.149)
There appears to be a bug open for Chrome 80 https://support.google.com/chrome/thread/29828561?hl=en, open since February, but not much is said about whether it will be fixed and how. Consider upvoting it.
According to a comment posted there, you could work around the issue by replacing the hour12
property with hourCycle: 'h23'
.
new Intl.DateTimeFormat(
'en',
{
weekday: 'long',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hourCycle: 'h23'
}
).format(new Date('2020-03-11T23:59:00Z')
)
// "Thursday, March 12, 00:59"
This seems to do the trick for me
The issue seems to be the default setting for HourCycle and langauge en
, which you'd expect to be h23
, but Chrome is using h24
. You can fix it as described by toniedzwiedz, or you can provide a suitable country code for the language tag to force the HourCycle to default to h23
, say GB:
let d = new Date(2020,2,1,0,23);
let opts = { hour12: false, hour: 'numeric' };
console.log(d.toLocaleString('en', opts)); // 24 (Chrome), 00 others
console.log(d.toLocaleString('en-GB', opts)); // 00 all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With