Home > OS >  about Date operation no correct problem in google Appscript
about Date operation no correct problem in google Appscript

Time:08-14

  var lastrow = SS.getLastRow()
  var lastday = SS.getRange("A"  lastrow).getValue(); //Thu Dec 31 11:00:00 GMT-05:00 2009 = 2010-01-01 (GMT  8)
  var today = SS.getRange("C2").getValue();
  var diffInDays = Math.floor((today-lastday)/(24*3600*1000));

  //Creat DateAr |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
  Logger.log(diffInDays)
  var AddingAr =[]
  for (var i = 1; i < diffInDays ; i = i   1) {

    var d_date = new Date();
    d_date = d_date.setDate(lastday.getDate()  i )
    var d_dateString = Utilities.formatDate( new Date(d_date) , "GMT 8", "yyyy-MM-dd")
    AddingAr.push([d_dateString])
    Logger.log("lastday: "  lastday "  i:"  i   " =d_date: "  d_date  " = "   d_dateString)

  }

  Logger.log(AddingAr)
  Logger.log(AddingAr.length)
  SS.getRange(lastrow   1, 1,AddingAr.length).setValues(AddingAr)

as seem , //Thu Dec 31 11:00:00 GMT-05:00 2009 = 2010-01-01 (GMT 8) d_date = d_date.setDate(lastday.getDate() i ) //in for loop

2010-01-01 1 should be 2010-01-02 log:2022-09-02 2010-01-01 2 should be 2010-01-03

i have no idea why 2010-01-01 1 is 2022-09-02

Log:

lastday: Thu Dec 31 2009 11:00:00 GMT-0500 (Eastern Standard Time)  i:1 =d_date: 1662023267434 = 2022-09-01
下午5:07:47   資訊  lastday: Thu Dec 31 2009 11:00:00 GMT-0500 (Eastern Standard Time)  i:2 =d_date: 1662109667441 = 2022-09-02
下午5:07:47   資訊  lastday: Thu Dec 31 2009 11:00:00 GMT-0500 (Eastern Standard Time)  i:3 =d_date: 1662196067443 = 2022-09-03
下午5:07:47   資訊  lastday: Thu Dec 31 2009 11:00:00 GMT-0500 (Eastern Standard Time)  i:4 =d_date: 1662282467445 = 2022-09-04
下午5:07:47   資訊  lastday: Thu Dec 31 2009 11:00:00 GMT-0500 (Eastern Standard Time)  i:5 =d_date: 1662368867447 = 2022-09-05

CodePudding user response:

The javascript Date object only refers to the day of the month, not the whole date

  • new Date() does not create an empty date object, but it creates the date of today including the time in hours, minutes and seconds.
  • If you execute console.log(new Date()) today, it will result in something like Tue Aug 08 2022 07:44:012 GMT-0500 (Eastern Standard Time)
  • Then, for example console.log(new Date().setDate(10)) will result in Tue Aug 10 2022 07:44:012 GMT-0500 (Eastern Standard Time)
  • What you want instead is to create a date object from your existing timestamp: var d_date = new Date(lastday); instead of var d_date = new Date();
  • Then, the rest of your code will work - if lastday is a valid date object
  • For better understanding
function myTestFunction(){
  var SS = SpreadsheetApp.getActiveSheet();
  var lastrow = SS.getLastRow()
  var lastday = SS.getRange("A"  lastrow).getValue();
  var d_date = new Date(lastday);
  console.log(d_date);
  console.log(d_date.setDate(10));
}
  • Related