Note the date format before changing it with PHP

I am looking for a way to check the date format before changing the format. My system allows users to upload spreadsheets and one of those fields is date of birth.

This is the biggest problem that I've encountered so far, - mm/dd/yy

vs mm/dd/yyyy

. I found an example of fixing this in PHP that converts a 2-digit year to a 4-digit year , but I don't always want to do that.

Is there a way to check the PHP

Date format in the If statement? I don't want to rely on counting since 1/1/1973

is the same number of digits as 01/01/73

but the year problem will be confused.

Does anyone have any ideas on how I can check the date format before manipulating it.

+3


source to share


2 answers


Try using the DateTime class . the default constructor can interpret your date strings. This should remove the need for conditional checks.

$date1 = "1/1/1973";
$date2 = "01/01/73";

$dt1 = new DateTime($date1);
$dt2 = new DateTime($date2);

echo $dt1->format("m/d/Y");     // prints as 01/01/1973
echo $dt2->format("m/d/Y");     // prints as 01/01/1973

      


EDIT



For two-digit years below 1970, you can try this, but it will work if and only if current and future data is entered in the form of four-digit years. Otherwise, people born between 2003 and 2069 will get their birthdays in 19xx.

Note. ... We're using 2003 because the OP indicated that all new entries would be hammered down to four-digit years and (at the time of posting) no one under the age of 13 would be using the software.

$format = "Y";

if(!is_numeric(substr($date, -4)))      // Checks for 2 digit year
{
    $yy = substr($date, -2);            // Gets 2 digit year
    $format = "y";

    if($yy < 70 && $yy > 2)             // Looking for 1903 to 1969 
    {
        $yy += 1900;

        // Rebuild the date string with 4 digit year
        $date = substr($date, 0, strlen($date) - 2) . $yy;
        $format = "Y";
    }
}

$delimiters = array("/", "-", ".");     // Different date delimiters to check

foreach($delimiters as $delim)
{
    if(strpos($date, $delim) !== false)
    {
        $dt = DateTime::createFromFormat("m" . $delim . "d" . $delim . $format, $date);
    }
}

echo $dt->format("m/d/Y");

      

+2


source


Is it possible for me to include this code in my SQL insert command?   '$date = '01/24/2006'; $date = date('Y-m-d', strtotime($date)); $sql = "INSERT INTO table SET date = '$date'";



0


source







All Articles