Can anyone please help me get the HH:MM am/pm
format instead of HH:MM:SS am/pm
.
My javascript code is :
function prettyDate2(time){ var date = new Date(parseInt(time)); var localeSpecificTime = date.toLocaleTimeString(); return localeSpecificTimel; }
It returns the time in the format HH:MM:SS am/pm
, but my client's requirement is HH:MM am/pm
.
Please help me.
Thanks in advance.
The toLocaleTimeString() method returns a string with a language-sensitive representation of the time portion of the date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .
To use the toLocaleTimeString() method without displaying seconds, set the hour and minute parameters in the method's options object, e.g. date. toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}) .
To get the current date and time in JavaScript, you can use the toLocaleString() method, which returns a string representing the given date according to language-specific conventions. To display only the time, you can use the toLocaleTimeString() method.
The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.
Here is a more general version of this question, which covers locales other than en-US. Also, there can be issues parsing the output from toLocaleTimeString(), so CJLopez suggests using this instead:
var dateWithouthSecond = new Date(); dateWithouthSecond.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
A more general version from @CJLopez's answer:
function prettyDate2(time) { var date = new Date(parseInt(time)); return date.toLocaleTimeString(navigator.language, { hour: '2-digit', minute:'2-digit' }); }
Original answer (not useful internationally)
You can do this:
function prettyDate2(time){ var date = new Date(parseInt(time)); var localeSpecificTime = date.toLocaleTimeString(); return localeSpecificTime.replace(/:\d+ /, ' '); }
The regex is stripping the seconds from that string.
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