【问题标题】:Get current Month Google Apps Script (a lot of IF-statements)获取当前月份的 Google Apps 脚本(大量 IF 语句)
【发布时间】:2015-10-26 10:22:25
【问题描述】:

我已经编写了一个脚本,可以在 Logger 中打印出当前月份。 我认为这可以通过 Arrays 以更好的方式完成。

这是我目前所拥有的:

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); 
}

【问题讨论】:

    标签: javascript google-apps-script


    【解决方案1】:

    有一个Utility

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

    【讨论】:

    • 如果你想得到完整的月份名称,使用MMMM而不是MMM
    【解决方案2】:

    这是一个版本,我将月份放在 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

    【讨论】:

      【解决方案3】:

      也许你可以使用 switch 语句:

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

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

      【讨论】:

      • 这与使用 IF 相同。看看另一个答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多