javascript 获取当前月份的 Google Apps 脚本(很多 IF 语句)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33343338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:23:06  来源:igfitidea点击:

Get current Month Google Apps Script (a lot of IF-statements)

javascriptgoogle-apps-script

提问by John Smith

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.

我已经完成了一个脚本,可以在 Logger 中打印出当前月份。我认为这可以通过 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); 
}

回答by Mogsdad

There's a Utilityfor that.

有一个实用程序

var currentD = Utilities.formatDate(date, Session.getScriptTimeZone(), "MMM");

回答by Rudie Visser

Here's a version where I put the months in an arrayand I simply use mtas the array index.

这是我将月份放在一个版本中array,我只是将其mt用作数组索引。

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

演示

回答by vic vic

Maybe you could use a switch statement:

也许你可以使用 switch 语句:

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.

或者您可以尝试在数组上存储月份名称并使用“mt”的值作为索引。