0

My function WeeklySalesPlan receives an array of all the registers from a spreadsheet.

I'm trying to get the Month from the date on the first row, which is formatted as a date in the spreadsheet.

Also, when doing a Logger.log of the date I see that it has this format:

dateFrom :Sat Jan 02 2021 00:00:00 GMT-0500 (Eastern Standard Time)

Which seems to me to be a valid date.

However when using getMonth() I'm getting a NaN result, which usually happens when the date isn't corret but I can't seems to find what is wrong with this date format..

Code:

function Test(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ws = ss.getSheetByName("SalesPlan");
  const lastData = ws.getRange(2, 1, 1, 6).getValues();
  WeeklySalesPlan(lastData)
  
}


function WeeklySalesPlan(lastData){
  //Debemos validar de que es un nuevo registro sin procesar
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ws = ss.getSheetByName("SalesPlan");

  if(lastData[0][5] == "Unprocessed"){
    //Debemos capturar todos los open deals que existen al momento
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = ss.getSheetByName("SalesPlanWeekly");
    
    var dateFrom = new Date(lastData[0][1]);
    var dateTo = new Date(lastData[0][2]);

    Logger.log('dateFrom :' + dateFrom)

    var salesPlan_MonthFrom = dateFrom.getMonth();
    Logger.log("salesPlan_MonthTo: " + salesPlan_MonthTo);

    var salesPlan_YearFrom = dateFrom.getYear();
    Logger.log("salesPlan_YearFrom: " + salesPlan_YearFrom);
    
    var salesPlan_Product = lastData[0][3];
    var salesPlan_Quantity = lastData[0][4];

    for(var i = 0; i < 31; i++){
      var e = new Date(salesPlan_YearFrom, salesPlan_MonthFrom, i + 1, 0, 0, 0, 0);
      var day = e.getDay();
      
      var firstWeekBegin = 1;
      if(day == 1){
        break;
      }else{
        firstWeekBegin = firstWeekBegin + 1;
      }
    }
    var firstWeekDate = new Date(salesPlan_YearFrom, salesPlan_MonthFrom, firstWeekBegin, 0, 0, 0, 0);
    Logger.log("firstWeekDate: " + firstWeekDate);
  }
}

enter image description here

  • 2
    Parsing a date from a string using the `Date` constructor (or using `Date.parse`, which is what the `Date` constructor uses internally) is always a risk. See [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552). Also, you should use `getFullYear()` if you expect to use the year for calculations or anything interesting. – Heretic Monkey Jan 18 '21 at 02:01
  • 1
    *getMonth* will only return NaN if it's called on an invalid date. What is the value of *dateFrom*? What is the value of *lastData[0][1]*? – RobG Jan 18 '21 at 03:16

0 Answers0