toLocaleString gives wrong 12 hour time

Viewed 1078

I am writing a simple JS app which requires time to be displayed in 12-hour format. For this, I'm using the toLocaleString of the Date class. But unfortunately, it returns the time at 12:05 to be 00:05 pm and 00:05 to be 00:05 am where I want it to show 12:05 pm and 12:05 am respectively.

Here is the way I use the function:

console.log(new Date("2020-08-15 12:15").toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short", hour12: true}));

console.log(new Date("2020-08-15 00:15").toLocaleString("en-GB", { dateStyle: "medium", timeStyle: "short", hour12: true}))

Is there a workaround or any other function to properly display the time at 12 o'clock?

Problem occurs only at 12 o'clock and something past 12

1 Answers

There are more options when defining details of the format. ie:

hourCycle:'h11'
hourCycle:'h12'
hourCycle:'h23'
hourCycle:'h24'

Heaps more options here...

https://www.w3schools.com/jsref/jsref_tolocalestring.asp

Alternatively, consider using the Australian format which does what you're looking for without any extra coding... :)

en-AU: 15/08/2020, 10:43:45 am
Related