我目前试图显示用户的时间而不显示秒。是否有一种方法,我可以这样做使用Javascript的.toLocaleTimeString()?

做这样的事情:

var date = new Date();
var string = date.toLocaleTimeString();

将显示用户的时间与每个单位,例如,目前显示为3:39:15 PM。我是否能够显示相同的字符串,只是没有秒?(例如下午3时39分)


当前回答

你可以设置选项,在这个页面上你可以设置,去掉秒,像这样

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

支持Firefox、Chrome、IE9+和Opera。在你的web浏览器控制台试试。

其他回答

只需将日期转换为字符串,然后连接所需的子字符串。

let time = date.toLocaleTimeString();
console.log(time.substr(0, 4) + time.substr(7, 3))
//=> 5:45 PM

我只能从用户的localeTimeString中得到小时

const americanTime = date.toLocaleTimeString("en-US", { timeZone: 'America/New_York', hour: 'numeric', hour12: false })
    
const timeInHours = americanTime; 

在本例中,我使用New_York作为用户的位置。

使用locale:

var date = new Date();
date.toLocaleTimeString('fr-FR', {hour: '2-digit', minute: '2-digit'})

由Date.prototype.toLocaleString返回的值是依赖于实现的,所以你得到你得到的。您可以尝试解析字符串以删除秒,但在不同的浏览器中可能有所不同,因此您需要考虑使用的每种浏览器。

使用Date方法创建自己的明确格式并不困难。例如:

function formatTimeHHMMA(d) {
  function z(n){return (n<10?'0':'')+n}
  var h = d.getHours();
  return (h%12 || 12) + ':' + z(d.getMinutes()) + ' ' + (h<12? 'AM' :'PM');
}

你可以试试这个,它能满足我的需求。

var d = new Date();
d.toLocaleTimeString().replace(/:\d{2}\s/,' ');

or

d.toLocaleString().replace(/:\d{2}\s/,' ');