如何仅显示来自 javascript date.toLocaleTimeString() 的小时和分钟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19407305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show only hours and minutes from javascript date.toLocaleTimeString()?
提问by Venki
Can anyone please help me get the HH:MM am/pm
format instead of HH:MM:SS am/pm
.
任何人都可以帮我获取HH:MM am/pm
格式而不是HH:MM:SS am/pm
.
My javascript code is :
我的 javascript 代码是:
function prettyDate2(time){
var date = new Date(parseInt(time));
var localeSpecificTime = date.toLocaleTimeString();
return localeSpecificTimel;
}
It returns the time in the format HH:MM:SS am/pm
, but my client's requirement is HH:MM am/pm
.
它以 格式返回时间HH:MM:SS am/pm
,但我客户的要求是HH:MM am/pm
.
Please help me.
请帮我。
Thanks in advance.
提前致谢。
回答by Dan Cron
Hereis a more general version of this question, which covers locales other than en-US. Also, there can be issues parsing the output from toLocaleTimeString(), so CJLopez suggests using this instead:
这是这个问题的更一般版本,它涵盖了 en-US 以外的语言环境。此外,解析 toLocaleTimeString() 的输出可能会出现问题,因此 CJLopez 建议改用它:
var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
回答by kalley
You can do this:
你可以这样做:
function prettyDate2(time){
var date = new Date(parseInt(time));
var localeSpecificTime = date.toLocaleTimeString();
return localeSpecificTime.replace(/:\d+ /, ' ');
}
The regex is stripping the seconds from that string.
正则表达式正在从该字符串中去除秒数。
A more general version from @CJLopez's answer:
来自@CJLopez 回答的更一般的版本:
function prettyDate2(time) {
var date = new Date(parseInt(time));
return date.toLocaleTimeString(navigator.language, {
hour: '2-digit',
minute:'2-digit'
});
}
回答by Mattias
Use the Intl.DateTimeFormatlibrary.
function prettyDate2(time){
var date = new Date(parseInt(time));
var options = {hour: "numeric", minute: "numeric"};
return new Intl.DateTimeFormat("en-US", options).format(date);
}
回答by Rahul Tripathi
You may also try like this:-
你也可以这样尝试:-
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;
}
or something like this:-
或类似的东西:-
new Date('16/10/2013 20:57:34').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "")
回答by Dan Alboteanu
I posted my solution here https://stackoverflow.com/a/48595422/6204133
我在这里发布了我的解决方案https://stackoverflow.com/a/48595422/6204133
var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills)
.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });