javascript 如何使用 .toLocaleTimeString() 而不显示秒数?

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

How do I use .toLocaleTimeString() without displaying seconds?

javascripttime

提问by javadog36

I'm currently attempting to display the user's time without displaying the seconds. Is there a way I can do this using Javascript's .toLocaleTimeString()?

我目前正在尝试显示用户的时间而不显示秒数。有没有办法使用 Javascript 的 .toLocaleTimeString() 来做到这一点?

Doing something like this:

做这样的事情:

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

will display the user's time with every unit, e.g. currently it displays 3:39:15 PM. Am I able to display that same string, just without the seconds? (e.g. 3:39 PM)

将显示每个单位的用户时间,例如当前显示 3:39:15 PM。我可以显示相同的字符串,只是没有秒吗?(例如下午 3:39)

回答by CJLopez

You can always set the options, based on this pageyou can set, to get rid of the seconds, something like this

您始终可以根据您可以设置的此页面来设置选项,以摆脱秒数,就像这样

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

Supported by Firefox, Chrome, IE9+ and Opera. Try it on your web browser console.

支持 Firefox、Chrome、IE9+ 和 Opera。在您的 Web 浏览器控制台上尝试一下。

回答by RobG

The value returned by Date.prototype.toLocaleStringis implementation dependent, so you get what you get. You can try to parse the string to remove seconds, but it may be different in different browsers so you'd need to make allowance for every browser in use.

Date.prototype.toLocaleString返回的值依赖于实现,所以你得到你得到的。您可以尝试解析字符串以删除秒数,但在不同的浏览器中可能会有所不同,因此您需要为每个正在使用的浏览器留出余地。

Creating your own, unambiguous format isn't difficult using Date methods. For example:

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

回答by Floris Looijesteijn

This works for me:

这对我有用:

var date = new Date();
var string = date.toLocaleTimeString([], {timeStyle: 'short'});

回答by Mickael Austoni

With locales :

使用语言环境:

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

回答by arg

I've also been looking for solution to this problem, here's what I eventually came up with:

我也一直在寻找这个问题的解决方案,这是我最终想出的:

function getTimeStr() {
    var dt = new Date();
    var d = dt.toLocaleDateString();
    var t = dt.toLocaleTimeString();
    t = t.replace(/\u200E/g, '');
    t = t.replace(/^([^\d]*\d{1,2}:\d{1,2}):\d{1,2}([^\d]*)$/, '');
    var result = d + ' ' + t;
    return result;
}

You can try it here: http://jsfiddle.net/B5Zrx/

你可以在这里试试:http: //jsfiddle.net/B5Zrx/

\u200E is some formatting character that I've seen on some IE version (it's unicode left-to-right mark).

\u200E 是我在某些 IE 版本上看到的一些格式化字符(它是 unicode 从左到右标记)。

I assume that if the formatted time contains something like "XX:XX:XX" then it must be time with seconds and I remove the last part, if I don't find this pattern, nothing is changed. Pretty safe, but there is a risk of leaving seconds in some weird circumstances.

我假设如果格式化的时间包含类似 "XX:XX:XX" 的内容,那么它必须是带秒的时间,我删除最后一部分,如果我没有找到这个模式,什么都不会改变。相当安全,但在某些奇怪的情况下可能会留下几秒钟。

I just hope that there is no locale that would change the order of formatted time parts (e.g. make it ss:mm:hh). This left-to-right mark is making me a bit nervous about that though, that is why I don't remove the right-to-left mark (\u202E) - I prefer to not find a match in this case and leave the time formatted with seconds in such case.

我只是希望没有语言环境会改变格式化时间部分的顺序(例如,将其设为 ss:mm:hh)。不过,这个从左到右的标记让我有点紧张,这就是为什么我不删除从右到左的标记 (\u202E) - 在这种情况下,我更喜欢不找到匹配项并留下在这种情况下,时间格式为秒。

回答by karma

You can try this, which is working for my needs.

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

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

or

或者

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

回答by Frank Eastes

I think the original question can easily be answered with something being overlooked so far: a simple string split. The time being returned is a text string, just split it on the ":" delimiter and reassemble the string the way you want. No plug ins, no complicated scripting. and here ya go:

我认为最初的问题可以很容易地用到目前为止被忽略的东西来回答:一个简单的字符串拆分。返回的时间是一个文本字符串,只需在“:”分隔符上拆分它,然后按照您想要的方式重新组合字符串。没有插件,没有复杂的脚本。来吧:

var myVar=setInterval(function(){myTimer()},1000);

function myTimer() {
    var d = new Date();
    currentNow = d.toLocaleTimeString();
    nowArray = currentNow.split(':');
    filteredNow = nowArray[0]+':'+nowArray[1];
    document.getElementById("demo").innerHTML = filteredNow;
}

回答by koanima

Here's a function that will do it, with comments that explain:

这是一个可以执行此操作的函数,并带有解释说明的注释:

  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
  }

Since, as others have noted, toLocaleTimeString() can be implemented differently in different browsers, this way gives better control.

正如其他人所指出的那样,toLocaleTimeString() 可以在不同的浏览器中以不同的方式实现,因此这种方式可以提供更好的控制。

To learn more about the Javascript Date object, this is a good resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

要了解有关 Javascript Date 对象的更多信息,这是一个很好的资源:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

回答by Emu

Even though this is an older question, I had the same one myself recently, and came up with a more simple solution using regular expressions and the string replace function as another alternative (no need for external js libraries or reliance on the ECMAScript Internalization API):

尽管这是一个较旧的问题,但我最近自己也遇到了同样的问题,并提出了一个更简单的解决方案,使用正则表达式和字符串替换函数作为另一种选择(不需要外部 js 库或依赖 ECMAScript 内部化 API) :

var d = new Date();
var localeTime = d.toLocaleTimeString();
var localeTimeSansSeconds = localeTime.replace(/:(\d{2}) (?=[AP]M)/, " ");

This approach uses a regex look-ahead to grab the :ss AM/PM end of the string and replaces the :ss part with a space, returning the rest of the string untouched. (Literally says "Find a colon with two digits and a space that is followed by either AM or PM and replace the colon, two digits, and space portion with just a space).

这种方法使用正则表达式前瞻来获取字符串的 :ss AM/PM 结尾,并用空格替换 :ss 部分,返回字符串的其余部分不受影响。(字面意思是“找到一个带有两位数字和一个空格后跟 AM 或 PM 的冒号,并将冒号、两位数字和空格部分替换为一个空格)。

This expression/approach only works for en-US and en-US-like Locales. If you also wanted a similar outcome with, say, British English (en-GB), which doesn't use AM/PM, a different regular expression is needed.

此表达式/方法仅适用于 en-US 和类似 en-US 的语言环境。如果您还想要类似的结果,例如不使用 AM/PM 的英式英语 (en-GB),则需要不同的正则表达式。

Based on the original questioner's sample output, I assume that they were primarily dealing with American audiences and the en-US time schema.

根据原始提问者的样本输出,我假设他们主要与美国观众和美国时间模式打交道。

回答by bradley

Simply convert the date to a string, and then concatenate the substrings you want out of it.

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

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