0

I want to protect the document from other users if a date in Column B1 + 2days is greater than today.

I had no problem with protection part, but I can't get the IF statements to work for some weird reason I can't understand.

This is the script where i compare dates:

ss = SpreadsheetApp.getActiveSheet();
send_date = ss.getRange("B1").getValue();
  limit = new Date(send_date.setDate(send_date.getDate()-2))
  limit.setHours(0,0,0,0)
  day0 = new Date();
  day0.setHours(0,0,0,0)
  ss.getRange("D1").setValue(day0);
  ss.getRange("D2").setValue(limit);
  ss.getRange("D3").setValue(limit>day0);
  ss.getRange("D4").setValue(limit<=day0);
  if (day0>limit) { ss.getRange("C1").setValue("can be edited");}
  else if (day0<=limit) { ss.getRange("C1").setValue("cannot be edited");}

I set hours/minutes/seconds etc to 0 because I only need to compare the dates day by day.

What happens after I run the script?

For example, if B1 = '2017-10-24', D1 sets to today ('2017-10-26'), D2 sets to ('2017-10-22').

D3, with limit>day0 comparison gets value FALSE, D4 limit<=day0 gets TRUE.

So far so good, but when it comes to IF statements, it seems that these comparisons are reversed.

In this example, C1 is set to 'can be edited'.

For me, that means that first comparison return FALSE, the second returned TRUE.

When I set date to a date in future (i.e. '2017-10-30'), D1-D4 fields get the right values, but C1 is set to 'cannot be edited'.

I'll be grateful for any help.

Ritesh Nair
  • 3,327
  • 1
  • 17
  • 24
PrzemekS
  • 13
  • 2
  • Possible duplicate of [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Tigger Oct 26 '17 at 09:50

1 Answers1

0

You can not compare two objects (day0 and limit) like that.

But, you can compare a value of those two objects. For example, using getTime().

var day0Time = day0.getTime();
var limitTime = limit.getTime();
if (day0Time > limitTime) {
    // do stuff
}
Tigger
  • 8,980
  • 5
  • 36
  • 40
  • I replaced day0 and limit with .getTime() values, but it still doesn't work. What grinds me is that even if i couldn't compare dates like that, condition in setValue works correctly (return TRUE) while the same condition in IF works the other way around. – PrzemekS Oct 26 '17 at 10:00
  • Something else may be wrong then. Dump to console the values of `*.getTime()` before the `if` statement. – Tigger Oct 26 '17 at 10:02
  • When B1 is '2017-10-24, .getTime() returns 1508968800000 current date is 1508623200000 – PrzemekS Oct 26 '17 at 10:21
  • That is a diff of 4 days exactly, so yer, problem is somewhere else. – Tigger Oct 26 '17 at 10:24
  • 1
    I think i found the solution myself. It works fine. Just the order of variables in if condition was wrong. Anyway, thanks for helping figuring this somehow out. – PrzemekS Oct 26 '17 at 10:31