简体   繁体   English

JavaScript Date toLocaleTimeString()的行为不符合预期

[英]JavaScript Date toLocaleTimeString() not behaving as expected

I have two timers on a page. 我在页面上有两个计时器。 One displays the Local Time and the other is a Timer from zero. 一个显示本地时间,另一个显示从零开始的计时器。

function go()
{
    startTime = Date.now();
    setInterval( updateTime, 1000);
}     

function updateTime() {
    var now = new Date();              
    sessionTime = new Date(Date.now() - startTime);      

    $("#session").text(checkTime(sessionTime.getHours()) + ":" +
        checkTime(sessionTime.getMinutes()) + ":" +
        checkTime(sessionTime.getSeconds()));


    $("#timer").text(checkTime(now.getHours()) + ":" + 
        checkTime(now.getMinutes()) + ":" + 
        checkTime(now.getSeconds())); 
};

function checkTime(i) {
    if (i <10) {
        i = "0" + i;
    }
    return i;
}

Unfortunately the element #sessionLocale returns 01:00:00 instead of the 00:00:00 I am expecting. 不幸的是,元素#sessionLocale返回01:00:00 ,而不是00:00:00我期待。

I delete the startTime from the 'now' time. 我从'现在'时间删除了startTime。 I then use that to extract the hours, minutes and seconds which gives me 00:00:00. 然后我用它来提取小时,分钟和秒,这给了我00:00:00。 But if I use the toLocaleTimeString I get 01:00:00. 但如果我使用toLocaleTimeString,我会得到01:00:00。

I want to use toLocaleTimeString for it's localisation options. 我想使用toLocaleTimeString来获取它的本地化选项。 Any ideas? 有任何想法吗?

This is working 这很有效

 function go() { startTime = Date.now(); setInterval( updateTime, 1000); } function updateTime() { var now = new Date(); sessionTime = new Date(Date.now() - startTime); // sessionTime.setHours(00); console.log(); sessionTimeL = new Date(Date.now() - startTime); $("#session").text(checkTime(sessionTime.getUTCHours()) + ":" + checkTime(sessionTime.getUTCMinutes()) + ":" + checkTime(sessionTime.getUTCSeconds())); $("#sessionLocale").text( pad(Math.floor(sessionTimeL * 1 / (1000 * 60 * 60) % 24), 2) + ':' + pad(Math.floor(sessionTimeL * 1 / (1000 * 60) % 60), 2) + ':' + pad(Math.floor(sessionTimeL * 1 / (1000) % 60), 2) ); $("#timer").text(checkTime(now.getHours()) + ":" + checkTime(now.getMinutes()) + ":" + checkTime(now.getSeconds())); console.log(sessionTime.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' })); } function checkTime(i) { if (i <10) { i = "0" + i; } return i; } function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; } go(); 
 <!DOCTYPE html> <html> <head> <script src="//code.jquery.com/jquery-2.1.1.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="session"></div> <div id="sessionLocale"></div> <div id="timer"></div> </body> </html> 

So here is the why. 所以这就是原因。 You are creating a new Date with 0 msec witch is equal to 1970 - 01 - 01 00:00:00 UTC so when you are in a different timeZone then UTC you get the Offset. 您正在创建一个新的日期,0毫秒女巫等于1970 - 01 - 01 00:00:00 UTC,所以当你在不同的时区,然后UTC你得到偏移。

You can either calculate the time difference or you could get the UTC hours with date.getUTCHours(). 您可以计算时差,也可以使用date.getUTCHours()获取UTC时数。 Or you get the UTC string and regex the time from it. 或者你得到UTC字符串和正则表达式的时间。 The solution I did is more secure to work. 我所做的解决方案更安全。

Working with Dates on Javascript can be troublesome sometimes due to the offset changing in different regions. 由于不同地区的偏移量变化,在Javascript上使用日期有时会很麻烦。

There's a library called DataJS which is super easy to implement, has really amazing performance and expands on the Date methods, adding functionality you might otherwise have to implement on your own. 有一个名为DataJS的库,它非常易于实现,具有非常出色的性能并扩展了Date方法,增加了您可能需要自己实现的功能。

For example to get the difference between two dates: 例如,要获得两个日期之间的差异:

var futureDate = new Date().add({months: 5, days: 4, hours: 3, minutes: 2, seconds: 1}); 

var now = new Date();

var timeSpan = new TimeSpan(futureDate - now);

console.log("Days:", timeSpan.getDays()); console.log("Hours:", timeSpan.getHours()); console.log("Minutes:", timeSpan.getMinutes()); console.log("Seconds:", timeSpan.getSeconds());

That way you can get a more human readable time span between two dates. 这样,您可以在两个日期之间获得更人性化的时间跨度。

Check the latest version in the SVN at https://code.google.com/p/datejs/source/browse/trunk/ . 通过https://code.google.com/p/datejs/source/browse/trunk/查看SVN中的最新版本。

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

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