Javascript - 日期计算中的意外行为

Javascript - unexpected behavior in dates calculations

我是新手,最近开始阅读 McPeak 和 Wilton 的《开始》Javascript。作者提出了一个关于日期计算的练习。这就是练习

Using the Date type, calculate the date 12 months from now.

我试着用这段代码解决了

//gets today's date
    var today = new Date(); 

//this line transforms the date in milliseconds    
var daysAsMilliseconds = 1000* 60 * 60 * 24 * today.getDate(); 

//creates a new Date object 
    console.log(new Date(today.setDate(365) + daysAsMilliseconds));

我这里得到的结果是正确的(2018 年 8 月 11 日)。

后来,我想知道是否真的需要创建2个变量并尝试了这个解决方案:

var today = new Date(); 
console.log(new Date(today.setDate(365) + (1000 * 60 * 60 * 24 * today.getDate())));

这里的解决方案不正确。控制台显示 2018 年 8 月 31 日。为什么?

如有需要,here you will find the repl.it with the code

您在调用 getDate 之前调用 setDate,因此 getDate 将始终 return 365. 只需交换它:

new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365))

或者直接使用月份可能更容易:

today.setMonth(today.getMonth() + 12);
var intwelvemonths = today;

您在添加 today.getDate() 的结果之前调用 today.setDate(365)today.getDate() 将给出您设置的日期,而不是今天的日期。

更改操作顺序即可解决问题:

var today = new Date(); 
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365));

您只需在年份上加 1:

var yearFromNow = new Date();
yearFromNow.setYear(yearFromNow.getFullYear() + 1);

将日期设置为 365 没有任何意义; .setDate() 用于日期,因此将其设置为该常量会将日期从上个月的最后一天(通常)移动一年。而且你不需要在日期 API 之外做任何其他数学运算;只需增加年份,就大功告成了。

我推荐你使用包 moment.js 因为它管理很多日期格式,而且它有很好的日期管理实现。

使用moment js进行添加

moment().add(Number, String);

例子

var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours(); // 5
m.add(1, 'days').hours(); // 5

有关更多文档,请参阅 moment().add() docs