1

I am using a small script to turn some lights on or off, but I can't seem to solve the following issue:

A PHP scripts runs as a daemon, gets a time setting from a database in the form HH:mm:ss

When I create a new dateTime instance like:

$TON = DateTime::createFromFormat('H:i:s', $time_on);    // i.e 16:00:00
$TOFF = DateTime::createFromFormat('H:i:s', $time_off);  // i.e 02:00:00

It creates an datetime object like this:

Time ON: 07-10-2019 16:00

Time OFF: 07-10-2019 02:00

Obviously the Off time is now wrong, so I check if TIME_OFF < TIME_ON and if so I add 24 hours the new object will then be:

Time ON: 07-10-2019 16:00

Time OFF: 08-10-2019 02:00

Which is now correct, but obviously as the script runs as a daemon, when passing over midnight, the datetime objects will change to the following:

Time ON: 08-10-2019 16:00

Time OFF: 09-10-2019 02:00

Causing the logic to break..

Are there any solutions to create a simple time check that works over midnight..?

Many Thanks!

martin010
  • 407
  • 1
  • 5
  • 14
  • 4
    You need to compare full DateTimes, with dates, not just times. – ceejayoz Oct 07 '19 at 13:47
  • `$TON = DateTime::createFromFormat('Y-m-d H:i:s', $time_on);` this should get the full date. – phainix Oct 07 '19 at 13:53
  • The only variable I have is the time. This is set. Date does not matter as it is a recurring process, it just needs to deal with changing over to midnight.. i.e one wants the lights to go on at 1600 and off at 0200 – martin010 Oct 07 '19 at 15:43
  • Why not working with exact timestamps instead of DateTime? – eisbehr Oct 09 '19 at 14:20

1 Answers1

0

You have to define an interval when the lights are on or off instead using only the hour.

So, define the LIGHTS_ON_INTERVAL

If the TIME_ON < TIME_OFF, the lights on interval is during the same day and there are no problems when passing over midnight and can be defined from the TIME_ON untill TIME_OFF

If TIME_OFF < TIME_ON (means that the time_off is the next day), the LIGHTS_ON_INTERVAL should be defined as the reunion between TIME_ON-midnight and midnight-TIME_OFF interval.

Finally, to switch the lights on or off, compare the current time with the LIGHTS_ON_INTERVAL considering the status of the lighs

beasst
  • 109
  • 8