我目前试图显示用户的时间而不显示秒。是否有一种方法,我可以这样做使用Javascript的.toLocaleTimeString()?
做这样的事情:
var date = new Date();
var string = date.toLocaleTimeString();
将显示用户的时间与每个单位,例如,目前显示为3:39:15 PM。我是否能够显示相同的字符串,只是没有秒?(例如下午3时39分)
我目前试图显示用户的时间而不显示秒。是否有一种方法,我可以这样做使用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浏览器控制台试试。
其他回答
你可以试试这个,它能满足我的需求。
var d = new Date();
d.toLocaleTimeString().replace(/:\d{2}\s/,' ');
or
d.toLocaleString().replace(/:\d{2}\s/,' ');
由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 dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
支持Firefox、Chrome、IE9+和Opera。在你的web浏览器控制台试试。
下面是一个函数,用注释解释:
function displayNiceTime(date){
// getHours returns the hours in local time zone from 0 to 23
var hours = date.getHours()
// getMinutes returns the minutes in local time zone from 0 to 59
var minutes = date.getMinutes()
var meridiem = " AM"
// convert to 12-hour time format
if (hours > 12) {
hours = hours - 12
meridiem = ' PM'
}
else if (hours === 0){
hours = 12
}
// minutes should always be two digits long
if (minutes < 10) {
minutes = "0" + minutes.toString()
}
return hours + ':' + minutes + meridiem
}
正如其他人所指出的那样,toLocaleTimeString()可以在不同的浏览器中以不同的方式实现,因此这种方式提供了更好的控制。
要了解更多关于Javascript Date对象的信息,可以参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
这对我来说很管用:
var date = new Date();
var string = date.toLocaleTimeString([], {timeStyle: 'short'});