How to show only hours and minutes from javascript date.toLocaleTimeString()?

前端 未结 5 1194
無奈伤痛
無奈伤痛 2020-12-16 11:02

Can anyone please help me get the HH:MM am/pm format instead of HH:MM:SS am/pm.

My javascript code is :



        
相关标签:
5条回答
  • 2020-12-16 11:49

    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.

    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'
      });
    }
    
    0 讨论(0)
  • 2020-12-16 11:49

    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' });
    
    0 讨论(0)
  • 2020-12-16 11:50

    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);
      } 
    
    0 讨论(0)
  • 2020-12-16 11:59

    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")
    
    0 讨论(0)
  • 2020-12-16 12:03

    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'});
    
    0 讨论(0)
提交回复
热议问题