简体   繁体   English

计算Javascript / ECMAScript中的时间跨度

[英]Calculating timespans in Javascript/ECMAScript

I've got a variable that holds a number of miliseconds which represents the timespan from now to a specified point in the future. 我有一个变量,它包含许多毫秒,表示从现在到未来指定点的时间跨度。

I want to convert this milisecond figure into a timespan value I can display to users. 我想将这个毫秒数字转换为我可以向用户显示的时间跨度值。

I know I can do this the naive way with modulo arithmetic and manually displaying the result to the user, but I want to do this using the Date() API built-in to Javascript/ECMAScript. 我知道我可以通过模运算和手动向用户显示结果的天真方式,但我想使用内置于Javascript / ECMAScript的Date()API来实现这一点。

This is how I generate it: 这是我生成它的方式:

var timespanInMS = timeInFuture.getTime() - now.getTime();
var diff = new Date( timespanInMS );

alert( "Hours: " + diff.getHours() + " Minutes: " + diff.getMinutes() );

However this only works when the user's computer is in the UTC timezone. 但是,这仅在用户的计算机处于UTC时区时才有效。 If they're in Pacific (UTC-8) then the value of 'diff' is off by 16 hours (even though the timespanInMS figure is the same). 如果他们在太平洋(UTC-8),那么'diff'的值将关闭16小时(即使timepanInMS数字相同)。

Thanks 谢谢

Perhaps getUTCHours and getUTCMinutes might work? 也许getUTCHoursgetUTCMinutes可能有效? See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date for more information. 有关更多信息,请参阅https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM