如果小时在午夜之后,则更改日期

时间:2016-10-30 21:00:16

标签: google-apps-script google-sheets

我是一个非常新的程序员。我正在尝试写一些能自动将日期放在我的床单上的东西。如果时间是午夜之后仍然不是早上6点我想要前一天的日期。这可能吗?

这是我到目前为止所拥有的;我被困了:

var CueectHoure = Utilities.formatDate(new Date(), "Asia/Jerusalem", "HH");
var CurrectDay = Utilities.formatDate(new Date(), "Asia/Jerusalem", "dd");
var CurrectMunth = Utilities.formatDate(new Date(), "Asia/Jerusalem", "MM");
var FullDay = CurrectDay + "." + CurrectMunth;
var fulldayless = CurrectDay -1 + "." + CurrectMunth;
var dayplus = CurrectDay - 31;
Browser.msgBox(dayplus);

// check if the hour is above 00 and under 6
if (CueectHoure > 00 & CueectHoure <= 6){

  //what happens if date is 1.11? we need return to 31.10        
  if (CurrectDay == 1){  
         CurrectDay = CurrectDay -1; // stuck here
  } else {

  }
  SpreadsheetApp.getActiveSheet().getRange('n1').setValue(FullDay);
  Browser.msgBox(FullDay);
}

1 个答案:

答案 0 :(得分:1)

简短回答

而不是减1,减去86400000并使用结果来获取新的Date对象。

解释

Google表格和Google Apps脚本使用不同的单位来表示日期时间值。虽然有一天是Google表格上的单位,但Google Apps脚本上只有一毫秒。

代码

function myFunction() {
  var oneDay = 24*60*60*1000;
  var today = new Date();
  var yesterday = new Date(today - oneDay);
  Logger.log('Today: %s', today.toLocaleDateString());
  Logger.log('Yesterday: %s', yesterday.toLocaleDateString());
}

日志

[16-10-30 19:05:08:315 CST] Today: October 30, 2016
[16-10-30 19:05:08:315 CST] Yesterday: October 29, 2016