hi all

Just a quick one I hope!

I am looping through a file and need to ensure that the date field value in the file is structured as:

dd/mm/yyyy

Is there a good quick way to do this?

Some users may type dd-mm-yyyy or something else which I need to detect.

If anyone can help i would be greatly appreciative!

Ta

    It's not completely foolproof but you could use strtotime() and then use date() to convert the timestamp to whatever format you want. strtotime() does not "know" all formats, but the most common. The idea is that you let that function convert all your dates to a timestamp (seconds) then you give the seconds to the date function and declares what format you want. Something like this:

    $ts = strtotime($input);
    $yourdate = date("d/m/y",$ts)
    

      Hi Undrium

      I do not need to convert the string, I actually need to validate the string to make sure it matches the dd/mm/yyyy structure.

      I am assuming a regular expression will do it but I am not familiar with these.

      Any help would be appreciated.

      Kind regards
      doug

        $pattern = '#\d{2}/\d{2}/\d{4}#';
        if (preg_match($pattern, $in))
        

        Do note that it still doesn't validate that day comes before month, or that it's even a date string. 31/01/2011 for 01 january 2011 would still pass, even though your format specifies that it should be 01/31/2011. 99/99/9999 would also pass the regexp.

        The regexp can of course be extended to start requiring that the first letter is a digit 1-2 followed by 0-9 or a 3 followed by 0-1 etc, but it quickly gets more complicated and I've no idea if you actually need to do that.

          Reguar expressions will help you match the correct pattern; to ensure that logical values are being passed, use something like [man]checkdate/man.

            Write a Reply...