简体   繁体   中英

How to check whether a php datetime variable is within range

I've checked the PHP manuals, and also googled prior to asking this question, but am still confused about how to do this correctly - How can I check whether my datetime variable's time part is greater than a given time?

Suppose I have a variable $time like the following:

$mdata['entry_date_time'] = $this->input->post('entry_date_time');
$time = $mdata['entry_date_time']->format('H:i:s');

What I want to do is something like this:

if($time > 12:00:00)
{
    //do something
}

My questions, based on the second code snippet, are:

  1. Is my syntax correct?
  2. If not, then what is the correct syntax?
  3. Is there any better approach to what I'm trying to do, other than my approach? If so, then what is it?

Depending on the format of the input, you could use datetime in this case:

$date_input = $this->input->post('entry_date_time');
$date = new DateTime($date_input);
if($date->format('H') > 12) {
    // do what you have to do
}

If you have a format that cannot be used directly on the constructor, you might need to use createFromFormat :

To answer fully:

  1. No, its not correct since most likely your post values are strings and therefore having -> an arrow operator doesn't make sense since its not an object.
  2. and 3. The answer above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM