Hello guys.

I'm sure someone can help me out with this, I've been googling but they're not what I'm after.

On my site, I ask staff members to input dates in one of two ways:

Either YYYY-MM-DD
Or YYYY-MM-DD HH:MM:SS

I check various other things, but I don't have a function that actually checks they're entered the date properly (i.e with the correct amount of -'s, only digits and the correct amount...)

Does anyone have a function I can use for each of these and how I check it?

Thank you!

    You could use a regular expression to see if the right format was entered:

    if(preg_match('/\d{4}-\d\d-\d\d( \d\d:\d\d:\d\d)?/', $date)
    {
       // it's valid
    }
    

    Another alternative would simply be to see if PHP strtotime() function recognizes it as any sort of valid date/time string:

    $unixTime = strtotime($date);
    if($unixTime <= 0 or $unixTime === false)
    {
       // invalid date/time
    }
    

      Thanks guys 🙂

      Dagon, that's the one I got too, but it confused me even further

      NogDog, both of those look promising, especially the one with the unix time for the larger one...

      The code you provided, is that ready to validate a yyyy-mm-dd?

      if(!preg_match('/\d{4}-\d\d-\d\d( \d\d:\d\d:\d\d)?/', $_POST['date'])
      {
       // Our error stuff here
      }
      

      The reason I ask is that it just has d's?

      Thanks!

        d = digit 0-9

        and its for matching YYYY-MM-DD HH:MM:SS

          Ah, okay

          So if this correctly validates YYYY-MM-DD HH:MM:SS

          if(!preg_match('/\d{4}-\d\d-\d\d( \d\d:\d\d:\d\d)?/', $_POST['date']) 
          { 
          // Our error stuff here 
          } 
          

          then would the following do for YYYY-MM-DD?

          if(!preg_match('/\d{4}-\d\d-\d\d/', $_POST['date']) 
          { 
          // Our error stuff here 
          } 
          

            The regexp will validate either format, as the " HH:MM:SS" portion is wrapped in parens as a sub-pattern followed by the "?" repetition modifier, which means "zero or one" of the preceding character or pattern. (Caveat: I did not test it, so there exists the possibility of stupid typos or a stupid programmer. 😉 )

              Write a Reply...