简体   繁体   中英

Checking if variable is date with PHP?

I have the following string:

08/07/2012 04:17:18

How can I check if it is a date data type by using PHP? For example, if I was checking for integer , I would do this: if(is_int($checkVar) . How can I do the same for date format of this kind?

date_parse($theString)

will return an array of the following format

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] => 
)

or false if it can't find a date. if that's enough for your needs, then use this!

You're not really checking if a variable is of type date . You have a string in a very specific format and want to make sure that it conforms with that format.

One way to do that, is with a regular expression ( preg_match() ). It's fairly simple to get something that's reasonably correct, but it might be hard if you also care about leap years, daylight savings time jumps, or if you're not ok with someone specifying February 30th.

The DateTime object can help you a little bit with that. You could parse out the inidivual components of your date, add it to the DateTime constructor and then see if the DateTime constructor comes up with something similar to the original input.

For example, I'm fairly sure that DateTime will convert April 31st (which doesn't exist) to May 1st manually. So you could check if your input month ( 4 ) matches the month DateTime is using ( 5 ). If all of those match up, and there was no error, it was a valid string in your format.

if (strtotime($date) !== false)

strtotime() returns numeric if the date is valid. Note that strtotime() and date_parse() also work on strings, so if you're validating for a DB and don't want stuff like

March 1st 2011

to work then you can't use these functions. For a mysql date I usually do

$date = date('Y-m-d',strtotime($date));

which formats any date format into the format needed. If the original $date was not in date format, the resulting $date will be false.

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