I have following three strings (current time, sunset and sunrise), how can I find if the current time is between the sunrise and sunset?
$current_time = "10:59 pm"; $sunrise = "5:42 am"; $sunset = "6:26 pm";
Interval Between Different Dates In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument.
The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.
Datetime objects are comparable, so you can compare datetime objects using the < , > , <= , >= , and == comparison operators. Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start , end , and current are datetime objects.
$current_time = "4:59 pm"; $sunrise = "5:42 am"; $sunset = "6:26 pm"; $date1 = DateTime::createFromFormat('h:i a', $current_time); $date2 = DateTime::createFromFormat('h:i a', $sunrise); $date3 = DateTime::createFromFormat('h:i a', $sunset); if ($date1 > $date2 && $date1 < $date3) { echo 'here'; }
See it in action
Reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With