[英]show time from milliseconds by using toLocaleTimeString()
I am attempting to show the time using milliseconds. 我试图以毫秒为单位显示时间。 I'm using the
toLocaleTimeString
since it supports the locale. 我正在使用
toLocaleTimeString
因为它支持语言环境。
var milliseconds = 10000; var date = new Date(milliseconds); console.log(date.toLocaleTimeString('en',milliseconds)); // expected result - 0:0:10 AM // actual result - 5:30:10 AM
The result is not what I'm expected. 结果不是我所期望的。 How can get the expected result using
toLocaleTimeString
如何使用
toLocaleTimeString
获得预期的结果
var date = new Date(10000);
is in UTC, ie 1970-01-01 00:00:10 UTC 以UTC表示,即1970-01-01 00:00:10 UTC
date.toLocaleTimeString('en')
output the time in your system timezone, thus gives the difference you found. date.toLocaleTimeString('en')
输出系统时区中的时间,从而给出您发现的时差。
One way to fix is to set date
variable to system timezone by adding the timezone difference in milliseconds, as the following: 解决方法之一是通过添加以毫秒为单位的时区差,将
date
变量设置为系统时区,如下所示:
var date = new Date(10000 + new Date().getTimezoneOffset()*60000);
( new Date().getTimezoneOffset()
is timezone difference in minutes) (
new Date().getTimezoneOffset()
是时区差异,以分钟为单位)
The normal behaviour of the .toLocaleTimeString()
method is to display the time in a string representation based on the local
time zone of your environment, that's why you got a different result. .toLocaleTimeString()
方法的正常行为是根据环境的local
时区以字符串表示形式显示时间,这就是为什么得到不同结果的原因。
And you were passing a wrong argument milliseconds
to it in: 您在其中传递了错误的
milliseconds
参数:
date.toLocaleTimeString('en',milliseconds);
Actually the Date.prototype.toLocaleTimeString() method takes an options
object as a second argument, where you can specify several options including the timeZone
which specifies the desired time zone for the output. 实际上, Date.prototype.toLocaleTimeString()方法将
options
对象作为第二个参数,您可以在其中指定多个选项,包括timeZone
,该timeZone
指定输出的所需时区。
So call it with {"timeZone": "UTC"}
to display it in UTC
, like this: 因此,与把它
{"timeZone": "UTC"}
中显示它UTC
,如下所示:
date.toLocaleTimeString('en',{"timeZone": "UTC"})
Demo: 演示:
var milliseconds = 10000; var date = new Date(milliseconds); console.log(date.toLocaleTimeString('en',{"timeZone": "UTC"})); // expected result - 0:0:10 AM // actual result - 5:30:10 AM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.