Javascript日期:什么是处理夏令时的最佳方式? [英] Javascript dates: what is the best way to deal with Daylight Savings Time?

查看:162
本文介绍了Javascript日期:什么是处理夏令时的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在上一个问题中,我写了一个javascript日期功能,在11/07/101神秘停止。感谢stackoverflow用户我被告知我的问题是夏令时间。 Javascript日期,这是我的错误还是我发现了一个错误?

In a previous question I wrote about a javascript date function that was mysteriously stopping on 11/07/101. Thanks to the stackoverflow users I was told my problem is Daylight Savings Time. Javascript date, is this my error or did I find a bug?

所以我最后一个问题是Javascript中处理夏令时的建议方法是什么?

So my last question on this is what is the recommended approach in Javascript to deal with Daylight Savings Time?

http://code.google.com/p/ datejs / 最好的方法来解决这个问题?

Is http://code.google.com/p/datejs/ the best approach to solve this?

推荐答案

最好的方法是不要处理DST。使用UTC方法,您不必担心越过DST边界或任何其他时区不连续性(区域设置时区规则可能会因为DST的更多原因而改变)。

The best way is not to deal with DST. Use the UTC methods and you won't have to worry about crossing a DST boundary, or any other timezone discontinuity (locale timezone rules can change for more reasons than just DST).

var timestamp= Date.UTC(2010, 10-1, 31, 0, 0, 0); // zero-based month: 9->october
var nextday= new Date(timestamp+86400000); // add one day
var ymd= [
    nextday.getUTCFullYear(),
    nextday.getUTCMonth()+1, // zero-based month
    nextday.getUTCDate()
].join('-');
alert(ymd); // 2010-11-1

如果以上是使用新的日期(2010,...) getDate()等,它会返回 2010-10-31 ,由于DST更改(在我所在的地区,无论如何),该天添加失败。

If the above had been done with new Date(2010, ...) and getDate() etc, it'd return 2010-10-31, the day add failing due to the DST change (in my region, anyway).

很遗憾,默认在 Date 中的明显方法是关于本地时间,特别是因为JavaScript实际上是为当地时间提供了很少的脚本上下文。 UTC是一个更稳定的命题。

It is a pity that the ‘default’ most-obvious methods in Date are about local time, especially since JavaScript provides so very little context to scripts on what ‘local time’ actually is. UTC is a more stable proposition.

这篇关于Javascript日期:什么是处理夏令时的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆