addDay()函数在Data.js中返回错误的值

时间:2012-11-17 10:58:25

标签: javascript datejs

我在我的网络应用中使用Date.js,当我从“Mon Oct 8 00:00:00 UTC-0300 2012”减去一天时,它返回“oct 6”而不是“oct 7”

这是我的代码:

var startTime = new Date(2012, 9, 8);
var beforeStare = startTime.clone().addDays(-1);

enter image description here

为什么会这样?如何解决这个问题?

并且我尝试了这个new Date(2012,9,7);它返回

  

oct 6 23:00:00 UTC-0300 2012

注意:我正在使用Asuncion(UTC-04:00) TimeZone

JSFiddler

2 个答案:

答案 0 :(得分:0)

您将日期转换为utc进行计算并在向用户显示时转换为本地时区,这样您就可以确保您使用的所有日期具有相同的标准。

// Creating the date "Oct 7 2012"
var date = new Date(2012, 9, 7);

//Convert to UTC in a safe way
var date_utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());

//Make the calculation in UTC format
var beforeStare_utc = date_utc.addDays(-1);

//Show to the user in his/her local time
var beforeStare = new Date(beforeStare_utc + " UTC");

这是JSFiddle

答案 1 :(得分:0)

JavaScript日期确切地知道两个时区:本地时间和UTC。您可以从第三个时区解析日期,但JavaScript会立即忘记该时区,并且只会根据当地时间或UTC告诉您该日期。

Mon Oct 8 00:00:00 UTC-0300 2012前一天Mon Oct 7 00:00:00 UTC-0300 2012。转换为当地时间-0400,即Mon Oct 6 23:00:00 UTC-0400 2012

Updated jsFiddle