Earth
Earth

Reputation: 13

Why does adding a month to a Date object return a strange number?

The following returns 11 which is correct.

var month = d.getMonth();
alert(month);

When I try adding a month to it returns something very different

var month = d.setMonth(d.getMonth() + 1);
alert(month);

It returns: 1513230546878

Upvotes: 1

Views: 220

Answers (4)

Leo Muller
Leo Muller

Reputation: 1483

//set date to now:
var d = new Date();
console.log(d);

//just checking
var month = d.getMonth();
console.log(month);

//add a month
d.setMonth(d.getMonth() + 1);

//now the month is one ahead:
console.log(d.getMonth());
console.log(d);

Upvotes: 0

Barr J
Barr J

Reputation: 10929

In java script, if you write this:

var month = d.setMonth(d.getMonth() + 1);

You get a timestamp. Meaning, an integer number representing the month you chose.

This is because, setDate accepts a dayValue parameter:

Date.setDate(dayValue)

Meaning that:

  var dt = new Date("Aug 28, 2008 23:30:00");
    dt.setDate(24);
    console.log(dt);

will result in:

Sun Aug 24 2008 23:30:00 //+ your standard gmt time 

For further inquire, see this Link

Upvotes: 0

Shalitha Suranga
Shalitha Suranga

Reputation: 1146

d.setMonth() method returns the updated timestamp value (See docs). That's why you got a long number.

If you want to get the month you will use as per below

var d = new Date("2017-10-03");
d.setMonth(d.getMonth() + 1);
var month = d.getMonth(); // get new month
alert(month);

hope it helps

Upvotes: 0

Vipin Kumar
Vipin Kumar

Reputation: 6546

Return values of methods that you are using in your code are as follows

  1. d.getMonth() - A Number, from 0 to 11, representing the month (Link)
  2. d.setMonth() - A Number, representing the number of milliseconds between the date object and midnight January 1 1970 (Link)

Please note, d.setMonth() will modify your Date object in place. So, if you want your code to work as expected, you can write as follows

var d = new Date()
var month = d.getMonth();
alert(month);

d.setMonth(d.getMonth() + 1);
alert(d.getMonth());

Upvotes: 1

Related Questions