javascript 从 toLocaleTimeString 中删除秒数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24086741/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:10:31  来源:igfitidea点击:

Remove seconds from toLocaleTimeString

javascriptregexdate

提问by mate64

The Date.prototype.toLocaleTimeString()method returns a string with a language sensitive representation of the time portion of this date. It is available for modern browsers.

Date.prototype.toLocaleTimeString()方法返回一个字符串,该字符串具有该日期时间部分的语言敏感表示。它适用于现代浏览器。

Unfortunately, the native function is not ableto prevent the output of seconds. By default, it outputs a time format like hh:mm:ssor hh:mm AM/PMetc.

不幸的是,本机函数无法阻止seconds输出。默认情况下,它输出类似hh:mm:sshh:mm AM/PM等的时间格式。

second: The representation of the second. Possible values are "numeric", "2-digit".

second第二个的表示。可能的值为“ numeric”、“ 2-digit”。

Source: MDN reference

来源:MDN 参考

This means, that you can not use something like {second: false}.

这意味着,您不能使用类似{second: false}.



I'm looking for a simple stupidsolution, to remove the secondsfrom a hh:mm:ssformatted string.

我正在寻找一个简单的愚蠢解决方案,从格式化的字符串中删除秒数hh:mm:ss

var date = new Date();
var time = date.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
console.log(time); // 15:24:07

This regular expressions don'twork:

这正则表达式工作:

time.replace(/:\d\d( |$)/,'');
time.replace(/(\d{2}:\d{2})(?::\d{2})?(?:am|pm)?/);

采纳答案by anubhava

You can use:

您可以使用:

var time = date.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'})
           .replace(/(:\d{2}| [AP]M)$/, "");

btw Google Chromereturns

顺便说一句Google Chrome返回

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

as "12:40 PM"

作为 "12:40 PM"

回答by Dalorzo

Just to add another possible combination to achieve this:

只是添加另一种可能的组合来实现这一点:

(new Date()).toLocaleTimeString().match(/\d{2}:\d{2}|[AMP]+/g).join(' ')