If, && function and time

 currentTime = String(hour()) + ":" + minute() + ":" + second();
    if ((currentTime >= "17:20:0") && (currentTime <= "17:20:5"))
    { 
        do something...
     }

is this gonna work properly?

Don't post snippets (Snippets R Us!)

and no it won't because you can't expect that alphabetical order is like mathematical order (eg like 17:20:5 and 17:20:50)

if you want. to compare time, the easiest way is to built a mathematical representation of your moment in the day for example number of seconds since midnight

unsigned long currentTime = 3600ul * hour() + 60ul * minute() + second();

this would let you compare moment of the same day

yep i want it run between 17:20:00 and 17:20:05

as discussed don't use text to do math, use numbers... :slight_smile:

you create a function like this

inline uint32_t secondsSinceMidnight(uint8_t h, uint8_t m, uint8_t s) {
 return 3600ul * h + 60ul * m + s;
}

then in your code you do

if (secondsSinceMidnight(hour(), minute(), second()) >=  secondsSinceMidnight(17,20,5)) {
  // on or after 17:20:05
  ...
} else {
  // before 17:20:05
  ...
} 

I think so. But it may fail with different times. Find out yourself.

yeah

void setup() {
  String t1 = "17:20:5";
  String t2 = "17:20:30";

  Serial.begin(115200);
  if (t1 > t2) {
    Serial.print(t1 + " is greater than " + t2); // crappy code with String
  } else {
    Serial.print(t1 + " is not greater than " + t2); // crappy code with String
  }
}

void loop() {}

➜ you'll get 17:20:5 is greater than 17:20:30

you would need to have all the times on 2 digits

thanks alot

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.