简体   繁体   中英

Google Sheets script date comparison not returning expected result

I wrote those two functions for Google Script Editor to extend into sheets to determine if an event is due given when it last occurred, and how often it should occur.

For example, a medication needs to be taken twice a day, and the last time it was taken was on 29 Mar 2020 12:00, so the function needs to return "Due" if the time now is 30 Mar 2020 01:00, because it's an hour after it's due, which on 30 Mar 2020 00:00.

The results that I'm getting aren't what I expected when calling "IsDue". Am I comparing the date/time to now correctly?

function ReturnFrequencyInDays( unit, quantity)  {
  switch(unit) {
    case "Hours":
      return quantity/24;
      break;
    case "Days":
      return quantity;
      break;
    case "Weeks":
      return quantity * 7;
      break;
    case "Months":
      return quantity * 30;
      break;
    case "Years":
      return quantity * 365;
      break;
    default:
      return "Invalid unit";
  }
}


function IsDue(how_often,unit,every,last_occurance){
  var currentTime=new Date();
  if (((ReturnFrequencyInDays(unit,every)/how_often) + last_occurance )<=currentTime) {
    return "Due";
  } else {
    return "Not Due";
  }
}

You need to provide a little more explanation about what you want the function to do. But I assume from your terminology that your trying to compare number of days to a date here:

var currentTime = new Date();
    if(((ReturnFrequencyInDays(unit,every)/how_often) + last_occurance)<= currentTime){
    return "Due";
  }

And that's not going to work. You can get number of milliseconds from a reference date with the valueOf() or the getMilliseconds() methods and then convert them to days but my guess is that is not really what you want either. So for a better answer please explain the intended usage a little better and how you intend to call the functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM