A
A
Anton Bannykh2020-04-08 13:53:49
Google Apps Script
Anton Bannykh, 2020-04-08 13:53:49

How to compare dates in different cells using script?

There is the following working piece of script:

while (i<=1500&&s.getRange(i, col1).setNumberFormat("0.000").getValue()===s.getRange(i+1, col1).setNumberFormat("0.000").getValue()&& s.getRange(i+1, col1).isBlank()===false) { 
      s.getRange(i, col1).setNumberFormat("dd.mm.yyyy");
      i++;
      count++;
      }

Its task is to go through the column until the first date mismatch and record their number in the count variable. But due to the fact that .setNumberFormat() is used, the script runs slower than we would like. Is there any way to compare dates without resorting to changing the cell format (the usual getRange().getValue() doesn't work here)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2020-04-09
@datwext

It also should not "plow". This is not a horse.
I tried to understand without an example what this code does, and came to the conclusion that all this should be changed at least to

const values = s.getRange(1, col1, s.getLastRow(), col1).getValues();
const count = values.filter(
  (row, i, arr) => arr[i + 1] && compareAsDate_(row[0], arr[i + 1][0])
);
console.log(count);

Date comparison function
/**
 *
 * @param {any} a
 * @param {any} b
 */
function compareAsDate_(a, b) {
  return (
    a && b && a.getTime && b.getTime && a.toDateString() === b.toDateString()
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question