LazioTibijczyk
LazioTibijczyk

Reputation: 1957

Adding months to date returns weird numbers

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 outcome is:

1622458745610

I don't understand why...

Upvotes: 5

Views: 1140

Answers (2)

Muhammad Usman
Muhammad Usman

Reputation: 10148

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);

Upvotes: 6

skovmand
skovmand

Reputation: 4422

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

Upvotes: 3

Related Questions