【问题标题】:How to show only hours and minutes from javascript date.toLocaleTimeString()?如何仅显示 javascript date.toLocaleTimeString() 的小时和分钟?
【发布时间】:2013-10-24 19:07:43
【问题描述】:

谁能帮我获取HH:MM am/pm 格式而不是HH:MM:SS am/pm

我的 javascript 代码是:

function prettyDate2(time){
  var date = new Date(parseInt(time));
  var localeSpecificTime = date.toLocaleTimeString();
  return localeSpecificTimel;
} 

它以HH:MM:SS am/pm的格式返回时间,但我的客户要求是HH:MM am/pm

请帮帮我。

提前致谢。

【问题讨论】:

    标签: javascript date


    【解决方案1】:

    Here 是这个问题的一个更通用的版本,它涵盖了除 en-US 之外的语言环境。此外,解析 toLocaleTimeString() 的输出可能会出现问题,因此 CJLopez 建议改用它:

    var dateWithouthSecond = new Date();
    dateWithouthSecond.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
    

    【讨论】:

      【解决方案2】:

      来自@CJLopez's answer的更通用版本:

      function prettyDate2(time) {
        var date = new Date(parseInt(time));
        return date.toLocaleTimeString(navigator.language, {
          hour: '2-digit',
          minute:'2-digit'
        });
      }
      

      原始答案(在国际上没有用处)

      你可以这样做:

      function prettyDate2(time){
          var date = new Date(parseInt(time));
          var localeSpecificTime = date.toLocaleTimeString();
          return localeSpecificTime.replace(/:\d+ /, ' ');
      }
      

      正则表达式正在从该字符串中删除秒数。

      【讨论】:

      • 请记住,对于非英语语言环境,此解决方案将不起作用,因为 \d 的正则表达式不会检测到数字。示例:date.toLocaleTimeString('ar')。因此,@Dan Cron 的答案更适合一般用途。
      • 这不适用于芬兰语或德语语言环境,因为分隔符是“.” (点)不是“:”。 @Dan Cron 的回答更好。
      • 这是一个错误的答案,应该删除,原因如上所述。
      【解决方案3】:

      使用Intl.DateTimeFormat 库。

       function prettyDate2(time){
          var date = new Date(parseInt(time));
          var options = {hour: "numeric", minute: "numeric"};
          return new Intl.DateTimeFormat("en-US", options).format(date);
        } 
      

      【讨论】:

        【解决方案4】:

        我在这里发布了我的解决方案https://stackoverflow.com/a/48595422/6204133

        var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills) 
                        .toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });
        

        // '7.04 AM'

        【讨论】:

          【解决方案5】:

          你也可以这样尝试:-

          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;
          }
          

          或类似的东西:-

          new Date('16/10/2013 20:57:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
          

          【讨论】:

            猜你喜欢
            • 2021-08-31
            • 2020-10-05
            • 2012-06-24
            • 2017-10-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-06
            • 1970-01-01
            相关资源
            最近更新 更多