How to show only hours and minutes from javascript date.toLocaleTimeString()?
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.
Solution 1:
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'});
Solution 2:
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.
Solution 3:
Use the Intl.DateTimeFormat library.
function prettyDate2(time){
var date = new Date(parseInt(time));
var options = {hour: "numeric", minute: "numeric"};
return new Intl.DateTimeFormat("en-US", options).format(date);
}
Solution 4:
I posted my solution here https://stackoverflow.com/a/48595422/6204133
var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills)
.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });
// '7.04 AM'
Solution 5:
You may also try like this:-
function timeformat(date) {
var h = date.getHours();
var m = date.getMinutes();
var x = h >= 12 ? 'pm' : 'am';
h = h % 12;
h = h ? h : 12;
m = m < 10 ? '0'+m: m;
var mytime= h + ':' + m + ' ' + x;
return mytime;
}
or something like this:-
new Date('16/10/2013 20:57:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")