简体   繁体   English

JavaScript日期对象-奇怪的行为

[英]JavaScript Date Object - Strange Behavior

I am new to JavaScript and attempting to convert some server-side code to it using NodeJS. 我刚接触JavaScript,并尝试使用NodeJS将一些服务器端代码转换为JavaScript。 A snippet is below; 以下是一个摘要; in general it takes a date and subtracts 2 weeks from it. 通常,它需要一个日期并从中减去2周。

Can anyone explain why the below happens? 谁能解释为什么发生以下情况?

var currentDate = new Date('05/12/2014 14:32');
currentDate.setDate(currentDate.getDate() - 14);
console.log(typeof currentDate);
console.log(currentDate);

Output: 输出:

object
Mon Apr 28 2014 14:32:00 GMT-0500 (CDT)

Now, all is well. 现在,一切都很好。 I've managed to subtract 14 days off of my date. 我已经设法减少了14天的约会时间。 However, it really isn't the 'currentDate' anymore so I want to assign it to say, 'futureDate' 但是,它真的不再是'currentDate'了,因此我想将其指定为'futureDate'

var currentDate = new Date('05/12/2014 14:32');
var futureDate = currentDate.setDate(currentDate.getDate() - 14);
console.log(typeof futureDate);
console.log(futureDate);

Output: 输出:

number
1398713520000

Ick. ck That's no good. 不好 it looks like it returned milliseconds since epoch or something as a number. 看起来从纪元或以数字形式返回的毫秒数。 Bad times. 艰难时期。 But how come if I do this, it does work... 但是,如果我这样做,它怎么会起作用呢?

var currentDate = new Date('05/12/2014 14:32');
currentDate.setDate(currentDate.getDate() - 14);
var futureDate = currentDate;
console.log(typeof futureDate);
console.log(futureDate);

Output: 输出:

object
Mon Apr 28 2014 14:32:00 GMT-0500 (CDT)

It just makes no logical sense to me. 这对我来说没有逻辑意义。 JavaScript is hurting my head. JavaScript伤了我的头。 I'd be grateful for any help in understanding what is happening here. 非常感谢您能帮助您了解这里发生的情况。 I know I can proceed and my script will work, but I'd like to understand what is going on. 我知道我可以继续并且我的脚本可以工作,但是我想了解发生了什么。

Thanks, Tom 谢谢汤姆

What actually happens in your code now is this : 现在,您的代码中实际发生的是:

var futureDate = currentDate.setDate(currentDate.getDate() - 14); var futureDate = currentDate.setDate(currentDate.getDate()-14);

You're setting the date of currentDate to currentDate.getDate() - 14 . 您正在将currentDate的日期设置为currentDate.getDate() - 14 currentDate.setDate returns the integer equivalent of that new date, and you save that to futureDate . currentDate.setDate返回与该新日期等效的整数 ,并将其保存到futureDate

You should save it as a Date, and not as an integer as it currently is. 您应该将其保存为日期,而不是当前的整数。

It's because futureDate is currently not a Date. 这是因为futureDate当前不是日期。 currentDate.getDate() - 14 will return just a number, but for you to make it into a Date, you should initialize futureDate as a date first, then use futureDate.setDate to assign it a new date value. currentDate.getDate() - 14将仅返回一个数字,但要使它成为Date,则应首先将futureDate初始化为日期,然后使用futureDate.setDate为其分配一个新的日期值。

var futureDate = new Date();
futureDate.setDate(currentDate.getDate() - 14);

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

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