Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a call to Javascript's Date library such as date.setMonth(date.getMonth()-1) return 1426456040720 here?

Why does a call to Javascript's Date library such as date.setMonth(date.getMonth()-1) return 1426456040720 here?

I expect you may get different numbers due to the timezone and culture.

I feel like I must be missing something, I'm sure this is how I've always decremented a month.

Here is a codepen:

http://codepen.io/hally9k/pen/pvMxBP?editors=101

var thisMonth = new Date();

console.log('this month: ' + thisMonth);

var lastMonth = thisMonth.setMonth(thisMonth.getMonth() - 1);

console.log('last month: ' + lastMonth); 
like image 604
hally9k Avatar asked Feb 11 '23 10:02

hally9k


1 Answers

The return value from .setMonth() is the ms since epoch of the date object. You can see that intended return value in the ECMAScript specification here.

.setMonth() modifies its Date object. You can obtain the new month value from that object with .getMonth() if you want the new month value.

If you just want the new month after you've changed it, you can do this:

var d = new Date();
console.log('this month: ' + d.getMonth());
d.setMonth(d.getMonth() - 1);
console.log('previous month: ' + d.getMonth()); 
like image 64
jfriend00 Avatar answered Feb 12 '23 22:02

jfriend00