简体   繁体   English

javascript日期操纵怪异

[英]javascript date manipulation weirdness

I want to create two dates that contain the beginning date of a month and the beginning date of the following month. 我想创建两个日期,其中包含一个月的开始日期和下个月的开始日期。 This is what I have: 这就是我所拥有的:

var TheMonth = "6.2012"; // as in june 2012
TheMonth = TheMonth.split(".")

var TheDisplayDate = new Date(parseInt(TheMonth[1], 10), (parseInt(TheMonth[0], 10) - 1), 1);

var TheUpperLimit = new Date(TheDisplayDate.getFullYear(), TheDisplayDate.getMonth(), 1);

//I'm adding a month here but it's not changing the month
TheUpperLimit.setMonth(TheUpperLimit.getUTCMonth() + 1);

The problem is that TheUpperLimit turns out to be the same date. 问题是TheUpperLimit原来是同一个日期。 I have a fiddle here to look at. 我在这里看一下小提琴。 What am I doing wrong? 我究竟做错了什么?

Thanks. 谢谢。

The problem is that you use getUTCMonth with setMonth instead of setUTCMonth . 问题是你使用getUTCMonthsetMonth而不是setUTCMonth It's more correct to use only UTC or only non-UTC methods together. 仅使用UTC或仅使用非UTC方法更为正确。 When you use setMonth and getMonth , it seems to work correct. 当你使用setMonthgetMonth ,它似乎工作正常。 But when you use UTC variations of these functions, it gives you 2 jul instead of 1 jul (in my time zone, at least). 但是当你使用这些函数的UTC变体时,它会给你2个jul而不是1个jul(至少在我的时区)。 I suggest you to use the following code to avoid complications with time: 我建议你使用以下代码来避免时间上的复杂化:

var TheMonth = "6.2012"; // as in june 2012
TheMonth = TheMonth.split(".");
var month = parseInt(TheMonth[0]);
var year = parseInt(TheMonth[1]);
var second_month = month + 1;
var second_year = year;
if (second_month > 12) {
    second_month = 1;
    second_year++;
}

var TheDisplayDate = new Date(year, month - 1, 1);
var TheUpperLimit = new Date(second_year, second_month - 1, 1);
console.log([TheDisplayDate, TheUpperLimit]);
// => [Date {Fri Jun 01 2012 00:00:00 GMT+0400 (MSK)}, 
//     Date {Sun Jul 01 2012 00:00:00 GMT+0400 (MSK)}]

According to your nick( @frenchie ), your local time is probably French time. 根据您的昵称( @frenchie ),您当地的时间可能是法国时间。 This means GMT + 2:00 . 这意味着GMT + 2:00

When you are setting for example: 当您设置示例时:

new Date(2012,5,1)

it means you have: 这意味着你有:

year=2012, month=June, day=1, hours=minutes=seconds=mseconds=0 

As GMT + 2:00 , UTC Date will have -2 hours offset. GMT + 2:00UTC Date将有-2小时的偏差。 If you would do TheUpperLimit.toString() , you will see, that you have Thu, 31 May 2012 22:00:00 GMT . 如果你要做TheUpperLimit.toString() ,你会看到,你有Thu, 31 May 2012 22:00:00 GMT This means, your UTC Month is '4'. 这意味着,您的UTC Month为“4”。 So when you are adding '+1' you will have '5' for month and it was June.So there is nothing wierd. 因此,当你添加“+1”时,你将有一个月份的'5',这是六月。所以没有什么是奇怪的。

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

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