Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 408
Venkaiah Yepuri Avatar asked Oct 16 '13 15:10

Venkaiah Yepuri


People also ask

What is toLocaleTimeString () in JavaScript?

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 .

How do I use toLocaleTimeString () without displaying seconds?

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'}) .

How do you get toLocaleString time?

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.

Can JavaScript handle dates and time?

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.


2 Answers

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'}); 
like image 160
Dan Cron Avatar answered Oct 05 '22 03:10

Dan Cron


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.

like image 30
kalley Avatar answered Oct 05 '22 03:10

kalley