# How to use time function?

Hello,
I got this time code for ESP32 and I want to make a LED turn on if the time is between 21:00 and 6:00.

The serial prints the correct time, but I don't know how to write the "if" function.

I need something like this but I don't know how to write it:

``````  if ((time > 21:00) && (time < 6:00 ))
{
digitalWrite (LED, HIGH);
}
``````

My code for time is:

``````void setup() {
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
setenv("TZ", "EET-2EEST,M3.5.0/3,M10.5.0/4", 1);
}

String get_time() {
time_t now;
time(&now);
char time_output;
// See http://www.cplusplus.com/reference/ctime/strftime/ for strftime functions
strftime(time_output, 30, "%a  %d-%m-%y %T", localtime(&now));
return String(time_output); // returns Sat 20-Apr-19 12:31:45
}

void loop()
{
delay(1000);
Serial.println(get_time());
}
``````

I have this

``````    time_t t = time(nullptr);
struct tm *tm = localtime(&t);
byte minute = tm->tm_min;
byte hour = tm->tm_hour;
``````

Thank you. And how can I write the "if" function with this?

simplest is to use minutes of the day

``````      minuteNow = hour * 60 + minute;
if (minuteNow >= (21 * 60 + 30)) ...
``````

Or if you are really only on the hour, use the byte hour value @Juraj picks out of the tm struct.

Then you need an "or" test on the 24 hour value, if the hour is greater than or equal to 21 gets you to midnight OR if the hour is less than 6 gets you to dawn.

or

you could also say if the hour is less than 21 AND greater than or equal to 6.

It is never too soon to discover and look into

`````` De Morgan's Theorem
``````

I leave the googling to you.

a7

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