admin管理员组

文章数量:1426810

I'm trying to add months to my date but the result is pretty weird.

This is what I'm doing:

var date = new Date();
date = date.setMonth(date.getMonth() + 36);

and the oute is:

1622458745610

I don't understand why...

I'm trying to add months to my date but the result is pretty weird.

This is what I'm doing:

var date = new Date();
date = date.setMonth(date.getMonth() + 36);

and the oute is:

1622458745610

I don't understand why...

Share Improve this question asked May 31, 2018 at 11:01 LazioTibijczykLazioTibijczyk 1,9671 gold badge29 silver badges63 bronze badges 2
  • check the Examples and Return value sections developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Slai Commented May 31, 2018 at 11:09
  • Some methods like Array.prototype.map are pure, they don't modify the original. Some like Array.prototype.sort are destructive, calling them changes the target. The Date methods are mostly destructive. If you're used to pure ones, it can throw you. – Jared Smith Commented May 31, 2018 at 11:09
Add a ment  | 

2 Answers 2

Reset to default 6

Date.prototype.setMonth() returns the number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.

and you are equating it with date here

date = date.setMonth(date.getMonth() + 36);

so date has now the value returned by setMonth.

Use

date.setMonth(date.getMonth() + 36);

to set month for a specified date

Now log this to see the output:

console.log(date);

The result you are getting is the number of milliseconds between 1 January 1970 and the updated date.

Convert it back to a date object like this: let d = new Date(1622458745610)

However, you don't need to retrieve the date as a variable. setMonth will mutate the date directly.

So just do:

var date = new Date();
date.setMonth(date.getMonth() + 36);
console.log(date);   // Date 2021-05-31T11:06:54.215Z

本文标签: javascriptAdding months to date returns weird numbersStack Overflow