5

I have done a script that prints out the current month in the Logger. I think this could be done in a better way with Arrays.

This is what I have so far:

function myFunction() {

var date = new Date();
var mt = date.getMonth();
var currentD     

  if  (mt === 0) {
   currentD = "JAN (qty)";
  }if (mt === 1) {
   currentD = "FEB (qty)";
  }if (mt === 2) {
   currentD = "MAR (qty)";
  }if (mt === 3) {
   currentD = "APR (qty)";
  }if (mt === 4) {
   currentD = "MAJ (qty)";
  }if (mt === 5) {
   currentD = "JUNI (qty)";   
  }if (mt === 6) { 
   currentD = "JULY (qty)"; 
  }if (mt === 7) {
   currentD = "AUG (qty)";  
  }if (mt === 8) {
   currentD = "SEP (qty)";  
  }if (mt === 9) {
   currentD = "OKT (qty)";  
  }if (mt === 10){
  currentD = "NOV (qty)";
  }else if (mt === 11){
  currentD = "DEC (qty)";
  }

 Logger.log("Current Month is: " +currentD); 
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
John Smith
  • 387
  • 2
  • 8
  • 24

3 Answers3

22

There's a Utility for that.

var currentD = Utilities.formatDate(date, Session.getScriptTimeZone(), "MMM");
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
9

Here's a version where I put the months in an array and I simply use mt as the array index.

function myFunction() {
    var date = new Date();
    var mt = date.getMonth();
    var months = ["JAN", "FEB", "MAR", "APR", "MAJ", "JUNI", "JULY", "AUG", "SEP", "OKT", "NOV", "DEC"];

    var currentD = months[mt] + " (qty)"; 

    Logger.log("Current Month is: " +currentD); 
}

DEMO

Rudie Visser
  • 570
  • 6
  • 23
2

Maybe you could use a switch statement:

function monthToString(mt){

  switch (mt){
    case 0: return "JAN (qty)";
    case 1: return "FEB (qty)";
    case 2: return ...
    ...
    default: return "Unknown"
  }

}

Or you can try storing month names on array and use the value of "mt" as index.

vic vic
  • 78
  • 1
  • 6