0

I am sorry, this is bound to be a REALLY easy answer to a silly question, but I am suffering from brain freeze!

I want a function that will return true if the current time is between the start and end time so the app won't run. Effectively a "quiet time";

A user can set a start time and and end time in 24hr clock:

$start_time = "0300"; $end_time = "0900"; 

Using the following almost works:

function isQuietTime($start,$end) { if((date("Hm") >= $start) && (date("Hm") <= $end)) {return TRUE;} else {return FALSE;} } 

But what if the start time is 2300, the end time is 0600 and the current time is 0300? The above function will return false. The problem occurs when the start time is before the end of the current day and the end time is the following day. How do I get this to work?

Thanks!

1
  • 1
    use a unix timestamp. Commented Aug 13, 2013 at 22:08

2 Answers 2

4
function fixedIsQuietTime($start, $end) { if ($start < $end) return isQuietTime($start, $end); else return ! isQuietTime($end, $start); } 
Sign up to request clarification or add additional context in comments.

4 Comments

Aha, very cunning! I was kind of hoping it would be one function and not two, but it does work. Any thoughts on how I could amalgamate the two functions into one?
Oh, I suppose something like this would work... function isQuietTime($start,$end,$now) { if ($start < $end) { if(($now >= $start) && ($now <= $end)) {return TRUE;} else {return FALSE;} } else { if(($now >= $start) && ($now <= $end)) {return FALSE;} else {return TRUE;} } }
You're right. By the way the developer who was implementing the alarm clock in my smartphone did not solve a similar problem - if you set an alarm at 11pm for 7am, it will ring at 7am a week later :). Good luck!
Thanks for your help. Also good to know I wasn't being too silly in asking the question! :-)
1

I would recommend using UNIX time. So write a function to convert the input time to a UNIX time. Something like this:

function to_unix_time($string){ // Something like this... $unix_time = mktime(); return $unix_time; } function isQuietTime($start, $end){ $now = time(); $stime = to_unix_time($start); $etime = to_unix_time($end); if($now > $stime && $now < $etime){ //its quiet time! return true; } } 

1 Comment

Thanks for your answer. Ideally I'd like to avoid converting to unix time for my app, but I like your thinking!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.