ExpressHaifa
ExpressHaifa

Reputation: 1

Change date if the hour is after after midnight

I'm a really new programmer. I'm trying to write something that automatically puts the date on my sheets. If the time is after midnight and still not 6AM I want the previous day's date. Is this possible?

This is what I have so far; I'm stuck:

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

Upvotes: 0

Views: 574

Answers (1)

Wicket
Wicket

Reputation: 38140

Short answer

Instead of substract 1, substract 86400000 and use the result to get a new Date object.

Explanation

Google Sheets and Google Apps Script use different units for datetime values. While one day is the unit on Google Sheets, on Google Apps Script is one millisecond.

Code

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

Logs

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

Upvotes: 1

Related Questions