I recreated your scenario, but instead of using strtotime
I used the DateTime
object.
Your main problem is that your first date ($data['sunset']
) must be considered as a real date, but your second date ($data['variation_turn_on']
) must be considered as an interval. Because of this, and after looking at the DateInterval
object constructor, you notice that you can create an interval using sscanf from your initial string. After creating that interval, all you have to do is to use the methods from the DateTime class to simply add or substract intervals from a specific date.
Here is the code I wrote to obtain the results you expect (6:00:00 AM and 2:00:00 AM) :
<?php
/* Initial parameters */
$data['turn_on_before_or_after'] = "before";
$data['sunset'] = "4:00:00 AM";
$data['variation_turn_on'] = "2:00:00";
/* Creating a list with your variation values */
list($hours, $minutes, $seconds) = sscanf($data['variation_turn_on'], '%d:%d:%d');
/* Creating the interval (here is the magic) */
$intervale = new DateInterval(sprintf('PT%dH%dM%dS', $hours, $minutes, $seconds));
/* Creating a DateTime object from your sunset time */
$date = new DateTime($data['sunset']);
/* Ternary for simplification, substract if before, add if everything else, you may use an if statement here */
$data['turn_on_before_or_after'] == 'before' ? $date->sub($intervale) : $date->add($intervale);
/* Printing the result */
echo $date->format('h:i:s A');