Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check date format before changing it with PHP

Tags:

date

php

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

This biggest issue I have run into this so far is mm/dd/yy vs mm/dd/yyyy. I have found an example of fixing this on PHP convert 2 digit year to a 4 digit year however I don't always want to do this.

Is there a way I can check the PHP Date format in an If statement? I don't want to rely on counting as 1/1/1973 is the same amount of digits as 01/01/73, but the year issue would get messed up still.

Anyone have any ideas on how I can check dateformat before manipulating it.

like image 774
Kyle Avatar asked Apr 08 '26 10:04

Kyle


1 Answers

Try using the DateTime class. The default constructor can interpret your date strings. This should void your 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 your current and future data is entered as four digit years. Otherwise people born between 2003 and 2069 will have their birthdays converted to 19xx.

Note: We're using 2003 because the OP indicated that all new entries will be forced to four digit years, and (at the time of posting) no one under 13 will 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");
like image 149
mjohns Avatar answered Apr 11 '26 01:04

mjohns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!