如何仅显示从javascript date.toLocaleTimeString()开始的小时和分钟

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

本文关键字:开始 小时 分钟 toLocaleTimeString 显示 何仅 javascript date      更新时间:2023-09-26

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

请帮助我。

下面是此问题的更通用版本,它涵盖了 en-US 以外的区域设置。此外,解析 toLocaleTimeString() 的输出可能存在问题,因此 CJLopez 建议改用这个:

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

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

正则表达式正在从该字符串中剥离秒数。

使用 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);
  } 

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

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

"上午7点04分"

你也可以这样尝试:-

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")