Welcome Guest, Not a member yet? Register   Sign In
How To Check A String Has A Valid DATETIME in it?
#1

[eluser]mdavis1982[/eluser]
Hi all...

I'm trying to implement a callback for the validation library that will check whether a string contains a valid DATETIME.

Is there some simple way I'm missing of seeing if the string contains a valid DATETIME? Like a built-in PHP function or something?

Thanks in advance for this... It's probably really simple, but I haven't done any coding for a couple of months so I'm a bit rusty!

Cheers...

Matt
#2

[eluser]xwero[/eluser]
The most common way is to enforce a certain datetime format as input you can check against. You can make it more gentle for the user by adding a javascript mask (jQuery masked input)
#3

[eluser]mdavis1982[/eluser]
Thanks for the advice...

I'd really like to check if a string contains a valid DATETIME in my code though. Obviously I'll be presenting the user with an interface that shouldn't allow him to put in an incorrect DATETIME, but you just never know... He may put in 31st September, or something (I hate relying on JS).

There must be some way of doing it!

Any more help would be greatly appreciated.

Thanks...

Matt
#4

[eluser]xwero[/eluser]
If you have an only English website you can try to parse the string with strtotime then it's possible to add something like next Thursday, 10 September 2000. The downside is the only check for a false date is when the parsed date is 1970-01-01.
#5

[eluser]mdavis1982[/eluser]
Thanks...

I think I have it now...

This code seems to work:

Code:
function check($dateTime)
{
    if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches))
    {
        if (checkdate($matches[2], $matches[3], $matches[1]))
        {
            return true;
        }
    }
    return false;
}

It seems to be parsing it all properly.




Theme © iAndrew 2016 - Forum software by © MyBB