Search code examples
dateif-statementgoogle-apps-scriptgoogle-sheetsgoogle-sheets-macros

Compare data with present date google script


Hi i want to compare column with date (i.e "Referral Date" column) image of column with present day , here is what i have

function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
  var headers = range.getValues()[0];
  var colIndex = headers.indexOf("Referral Date");
  var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
for (i=0;i<range.getLastRow();i++){
  var dates = searchRange.getValues();
      if (today.valueOf()>dates.valueOf()){
        updatelFilter()
      } else{
        SpreadsheetApp.getUi().alert('Future Date Error');
      break;
    }
  }
}

The problem i have is, it throws alert Future Date Error irrespective of date in column (Referral Date). Let me know if additional information is required.

My goal:

1)if date column (Referral Date) is greater than present date : Throw alert error & should not run updateFilter

2)if (Referral Date) is lesser than present date: Run updateFilter function


Solution

  • Issues

    1. searchRange.getValues() yields a two dimensional array. So dates[0][0] points to a date, while dates[0] points to an array.
    2. var dates = searchRange.getValues(); is being called inside the loop repeatedly, when it should ideally be called outside once since the value will not change; calling it inside the loop is costly and redundant
    3. for (i=0;i<range.getLastRow();i++){ the condition can be replaced with i<dates.length if point 2 is followed
    4. if (today.valueOf()>dates.valueOf()){ I believe is supposed to have dates[0] instead

    Modified Code

    function newF(){
      var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
      var range = ss.getDataRange();
      var headers = range.getValues()[0];
      var colIndex = headers.indexOf("Referral Date");
      var today = new Date();
      var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
      var dates = searchRange.getValues().map(d=>d[0]); 
    
      for (i=0;i<dates.length;i++) {
        if (today.valueOf()>dates[i].valueOf()){
          updateFilter()
        } else {
          SpreadsheetApp.getUi().alert('Future Date Error');
          break;
        }
      }
    }
    

    To run updateFilter only if no future dates

    Replace the loop with the following -

    if(dates.some(d => today.valueOf() < d.valueOf())) {
      SpreadsheetApp.getUi().alert('Future Date Error');
    } else {
    
      for (let i=0; i<dates.length; i++) {
        updateFilter();
      }
    }