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 likeArray.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
2 Answers
Reset to default 6Date.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
版权声明:本文标题:javascript - Adding months to date returns weird numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745464280a2659463.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论