Moment.js - 如何检测夏令时和添加一天 [英] Moment.js - How To Detect Daylight Savings Time And Add One Day

查看:2070
本文介绍了Moment.js - 如何检测夏令时和添加一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从2000年以来的每一天的每个小时的Date数据的字符串中创建Date Objects。

I need to create Date Objects from strings of Date data for every hour of every day since the year 2000.

每个小时的字符串看起来像这样,一个月/日/年小时格式...

The strings look like this for every hour, in a Month/Day/Year Hour format...

"04/02/2000 01", "04/02/2000 02", "04/02/2000 03" ...all the way to... "04/02/2000 24"

现在,我有以下代码,除了在夏令时的日子之外,还可以正常工作...

Now, I have the following code, which works fine except for on days with Daylight Savings Time...

  // Split At Space
var splitDate = "04/02/2000 24".split(/[ ]+/);
var hour = splitDate[1];
var day  = splitDate[0];
  // Split At Slashes
var dayArray = day.split("/");
if (hour === "24") {
       // Months are zero-based, so subtract 1 from the month
     date = new Date(Date.UTC( dayArray[2], parseInt(dayArray[0] - 1), dayArray[1], 0, 0, 0 ));
     date.setDate(date.getDate() + 1);
} else {
     // Months and Hours are zero-based, so subtract 1 from each
     date = new Date(Date.UTC( dayArray[2], parseInt(dayArray[0] - 1), dayArray[1], hour, 0, 0 ));
};

在夏令时的日子里,像 04/02/2000 添加一天不工作,如果小时是 24 。相反,它只返回 Sun,2000年4月02日23:00:00 GMT

On days with daylight savings time, like 04/02/2000 adding a day does not work if the hour is 24. Instead, it just returns Sun, 02 Apr 2000 23:00:00 GMT

使用Moment.js,是可以检测到DST的日期,并使此代码正常工作?

With Moment.js, is it possible to detect a DST day and get this code to work correctly?

推荐答案

要检测DST,请使用 .isDST()方法: http:// momentjs。 com / docs /#/ query / is-daylight-saving-time /

To detect DST, use the .isDST() method: http://momentjs.com/docs/#/query/is-daylight-saving-time/

moment([2011, 2, 12]).isDST(); // false, March 12 2011 is not DST
moment([2011, 2, 14]).isDST(); // true, March 14 2011 is DST

使用这个测试,你应该能够确定如何修改程序的行为。

Using this test, you should be able to determine how to modify your program's behavior accordingly.

这篇关于Moment.js - 如何检测夏令时和添加一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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