0

I am working on a requirement where I have 12 ion slides and the names of the slides are month names starting from the current month. For ex: If the current month is June, then the name of the first slide should start from June 2020 and go on till May 2021. Well I tried it but not able to achieve. Even if I handle the month, then I am not able to dynamically change the year after December. Here is my code:

my html file

  <ion-toolbar class="toolbars" #ionDragFooter>    
          <ion-title class="ion-text-center">{{currValue}}</ion-title>
  </ion-toolbar>

My .ts file

ngOnInit() {
 swipeNext()
}

 var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"];

  var d = new Date();


if(index == 1){
        var curMn=monthNames[d.getMonth()]+ d.getFullYear();
        console.log(curMn)
        this.currValue=curMn;
      }
      else if(index == 2){
        var curMn=monthNames[d.getMonth()+1]+ d.getFullYear();
        this.currValue=curMn;
      }
      else if(index == 3){
        var curMn=monthNames[d.getMonth()+2]+ d.getFullYear();
        this.currValue=curMn;
}

and so on for all other month. I need to completely automate the month and year starting from the current month. May I know where I went wrong?

Ravi Shah
  • 105
  • 1
  • 11
  • I assume the year is incorrect, since you never actually change the initial date `d`. What you could do instead is a loop and just increase the month by 1 in each iteration. Like `d.setMonth(d.getMonth() + 1)`. In either case you actually have to add the month to `d` to correctly increase your date variable and not juse use `d.getMonth()+2` to get the correct month translation. – Lain Jun 25 '20 at 18:06
  • Tried it but had issues with year – Ravi Shah Jun 25 '20 at 18:15

3 Answers3

3

You can create a date, then increment the month by 1 eleven times to get 12 months of dates. The month name can be found using toLocaleString with appropriate options.

You need to be careful when incrementing months, e.g.

let d = new Date(2020,0,31); // 31 Jan 2020
d.setMonth(d.getMonth() + 1) // 31 Feb 2020 -> 2 Mar 2020
d.toDateString();            // Mon Mar 02 2020

So best to set the date to the 1st of the month initially:

// Optionally provide a date for the starting month
function getMonthNames(date = new Date()) {
  // Copy input date so don't modify it
  let d = new Date(+date);
  // Set to 1st of month
  d.setDate(1);
  let result = [];
  // Get 12 month names, starting with current month
  for (let i=0; i<12; i++) {
    result.push(d.toLocaleString('default',{month:'long'}));
    d.setMonth(d.getMonth() + 1);
  }
  return result;
}

console.log(getMonthNames());
RobG
  • 142,382
  • 31
  • 172
  • 209
  • 3
    I like this approach yet I also must add that I am no fan of `toLocaleString()`. Usually users can choose languages independent of culture or local settings, which kinda meddles with this script. Furthermore for example if I watched that site all text would be in english yet the months are suddenly in french. Just something to be aware of. – JavaScript Jun 26 '20 at 05:30
  • @JavaScript—you're absolutely correct, the language option (inappropriately called "locale") should be set to the language of the page, so "en" in this case. I just used "default" for the sake of the demo. – RobG Jun 26 '20 at 05:51
  • Certainly. The issue with that is the lack of "locale" support. Unless it got fixed on various browsers by now. I admit I did not try it out in a while. – JavaScript Jun 26 '20 at 06:18
  • @JavaScript—support by current browsers is pretty good. According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString#Browser_compatibility) you have to go back a long way to miss out on "locales" support, even IE11 has it (released in 2013). – RobG Jun 26 '20 at 08:37
1

To properly change the date you have to increase the date by the amount of months in the date object (in your case d):

var d = new Date();

//REM: This will print out the next month, yet d still is unchanged
console.log(d.getMonth()+1);
console.log(d);
console.log('Month did not increase: ', d.getMonth());

//REM: You have to increase your date by one month in the date object
d.setMonth(d.getMonth() + 1);
console.log(d);
console.log('Month did increase: ', d.getMonth());

//REM: By which it will change the year for you, once it is time for it.
d.setMonth(d.getMonth() + 11); //REM: +1 from before
console.log(d);
console.log('Year did increase: ', d.getFullYear());

In your case that would be:

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

var d = new Date();
d.setDate(1); //REM: To prevent month skipping.

for(var i=0; i<12; i++){
  d.setMonth(d.getMonth() + 1);
  console.log(monthNames[d.getMonth()], d.getFullYear())
};

Some further reading on the issue

Lain
  • 3,657
  • 1
  • 20
  • 27
1

This is what I came up with:

const monthNames = ["January", "February", "March", "April", "May", "June",
     "July", "August", "September", "October", "November", "December"];
   
    const today = new Date();
    //gives you year
    const year = today.getFullYear();
    //gives you month as number/index;
    const month = today.getMonth();

    //stores sequenced month names
    const sequencedNames = [];

    //creates June 2020 through December 2020
    for(let i = month; i < monthNames.length; i++) {
        let monthName = monthNames[i];
        sequencedNames.push(monthName + " " + year)
    }
    
    //creates January 2021 through May 2021
    for(let i = 0; i < month; i++) {
        let monthName = monthNames[i];
        sequencedNames.push(monthName + " " + (year + 1))
    }

    console.log(sequencedNames)

Essentially 2 for loops, the first iterating from the current month to the end of the year, and then the second from the start of the year to the current month -- though adding 1 year.

Pavlos Karalis
  • 2,893
  • 1
  • 6
  • 14