SF23103 Posted March 27, 2016 Share Posted March 27, 2016 Hello, I am getting the sunset and sunrise time through an API that gives the time in these variables: $sunrise_hour , $sunrise_minute $sunset_hour , $sunset_minute I am putting them together to get the time of the sunset and sunrise: $sunset_time_formatted = "$sunset_hour:$sunset_minute PM"; Now, if I need to compare the sunset and sunrise time to the current time, ex: date("h:i A"); do I need to convert the $sunset_time_formatted to UNIX time first? The argument I came up with doesn't seem to work correctly. My guess is it needs to know how to read my sunrise and sunset formatted variables as a real time. if ($current_time > $sunrise_time_formatted && $current_time < $sunset_time_formatted) { echo "sun"; } else { echo "moon"; } Quote Link to comment https://forums.phpfreaks.com/topic/301091-comparing-times/ Share on other sites More sharing options...
Solution requinix Posted March 27, 2016 Solution Share Posted March 27, 2016 You can compare a) A date/time formatted as Y-m-d or Y-m-d H:i:s or H:i:s. Anything else probably won't work. The rules are complicated (I'll explain if you want) so stick to just those three formats. b) Unix timestamps c) DateTime objects Quote Link to comment https://forums.phpfreaks.com/topic/301091-comparing-times/#findComment-1532488 Share on other sites More sharing options...
maxxd Posted March 28, 2016 Share Posted March 28, 2016 Personally, I'd use DateTime objects. Right now you're comparing strings which technically does work thanks to PHP's loose typing, but it can lead to hard-to-pinpoint bugs and odd behavior. Not sure what responses your API gives, but if you try to compare "INVALID_ACCESS_TOKEN:INVALID_ACCESS_TOKEN PM" to "12:53 PM", it's going to give weird results. Obviously. However, an incorrectly formatted time string in the constructor of a DateTime object will throw an error that you can handle. Plus, I just find the DateTime objects easier to work with when it comes to comparisons and any mathematical operations. 1 Quote Link to comment https://forums.phpfreaks.com/topic/301091-comparing-times/#findComment-1532507 Share on other sites More sharing options...
SF23103 Posted March 28, 2016 Author Share Posted March 28, 2016 Thank you both! Based on both of your suggestions, I went with DateTime objects, and it's working great. That's a good point about error handling.. so I'll work on that next. Also, I see that PHP even has a date_sunset that returns the time of sunset (also one for sunrise) for a given day and location. Pretty cool, maybe I'll play with that too. Quote Link to comment https://forums.phpfreaks.com/topic/301091-comparing-times/#findComment-1532514 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.