Search code examples
javascriptdate

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.


Solution

  • 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.