32

谁能帮我获取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.

请帮我。

提前致谢。

4

5 回答 5

54

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

var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
于 2015-09-23T13:48:54.787 回答
36

来自@CJLopez 答案的更通用版本:

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+ /, ' ');
}

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

于 2013-10-16T15:24:09.543 回答
5

使用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);
  } 
于 2013-10-16T15:30:53.660 回答
2

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

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

// '7.04 上午'

于 2018-02-03T09:04:16.767 回答
1

你也可以这样尝试:-

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")
于 2013-10-16T15:24:34.450 回答