简体   繁体   中英

How to get previous 6 months date from current date in javascript

I am trying get last six months date from current date .

 var d = new Date(); var months = ["January","February","March","April","May","June","July","August","September","October","November","December"]; alert(months[d.getMonth()-6]); 

but i am getting udefined

I always recommend using date libraries to assist in these types of calculations. One of the most popular with a ton of support and examples is moment.js ( https://momentjs.com/ )

To get six months ago from the current date using moment is:

moment().subtract(6, 'months')

and then to print the month name would be:

moment().subtract(6, 'months').format('MMMM')

 var d = new Date(); var months = ["January","February","March","April","May","June","July","August","September","October","November","December"]; var monthName = months[new Date(d.setMonth(d.getMonth() - 6)).getMonth()]; console.log(monthName) 

You have to write your code like below-

var d = new Date();
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  d.setMonth(d.getMonth() - 6);
  console.log(months[d.getMonth()]);

We need to get Month from date object the set to back (with - 6) then get it back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM