Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

Trying to check for time above 9am in php but wont take any thing above 10?

I'm simply trying to check if the time is either above 9am or below 6pm, the 6pm check works fine and displays the data where as 9am one does nothing but works when changed to 10am.

Here is the line of code I'm using

elseif ((($data[6]) < "09:00") || (($data[6]) > "18:00"))
             {
             $contact[] = $data;
             }
question from:https://stackoverflow.com/questions/65617626/trying-to-check-for-time-above-9am-in-php-but-wont-take-any-thing-above-10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, let us assume that your time format is always hh:mm. You want to check if the time is between 9 and 18 hours. The problem in your code, as you described, comes when you are check again 09:mm. As it strips away the minute part and just compares the hours.

I would try something like this:

elseif ( implode("", explode(":", $data[6])) > 900 && implode("", explode(":", $data[6])) < 1800)

I will explain the approach step by step.

  1. First of all, this code checks if the date is within the range of 09:00 to 18:00. The code you have provided tested if it is less than 9 or more than 18.

  2. Let us focus on one part of the code, that will explain the whole thing as well:

    implode("", explode(":", $data[6])) > 900

First, we separate hours and minutes using the explode function. This gives us an array with two values.

`[0] => hh,`
`[1] => mm`

Now that we have separated this value we implode or concatenate them using the implode function that has no separator.

Next, instead of testing against the string, we test against the number. 09:00 is the same as 900 in this case.

Thus, we can check if the time is within the required limits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...