javascript - Adding months to date returns weird numbers - Stack Overflow

I'm trying to add months to my date but the result is pretty weird.This is what I'm doing:var

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745464280a4628847.html

相关推荐

  • javascript - Adding months to date returns weird numbers - Stack Overflow

    I'm trying to add months to my date but the result is pretty weird.This is what I'm doing:var

    8小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信