Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if time is between two times in PHP [duplicate]

Tags:

php

time

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"; 
like image 391
user966582 Avatar asked Apr 09 '13 19:04

user966582


People also ask

Can you compare time in PHP?

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.

What is Strtotime PHP?

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.

How do you check if a time is between two times in python?

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.


1 Answers

$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

  • DateTime
like image 174
John Conde Avatar answered Sep 21 '22 06:09

John Conde