简体   繁体   English

在使用PHP更改之前检查日期格式

[英]Check date format before changing it with 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 . 到目前为止,我遇到的最大问题是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. 我已经找到了一个在PHP转换2位数年到4位数年固定这个的例子,但我并不总是想这样做。

Is there a way I can check the PHP Date format in an If statement? 有没有办法可以在If语句中检查PHP日期格式? 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. 我不想依靠计数为1/1/1973是同样数额的数字01/01/73 ,但今年的问题会得到还是搞砸了。

Anyone have any ideas on how I can check dateformat before manipulating it. 任何人对如何在操作之前检查dateformat有任何想法。

Try using the DateTime class . 尝试使用DateTime类 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. 对于1970年以下的两位数年份,您可以尝试这一点,但是当且仅当您将当前和未来数据输入为四位数年份时,它才会起作用。 Otherwise people born between 2003 and 2069 will have their birthdays converted to 19xx. 否则,2003年到2069年之间出生的人将把他们的生日转换为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. 注意: 我们正在使用2003,因为OP表示所有新条目将被强制为四位数年份,并且(在发布时)13岁以下的人不会使用该软件。

$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");

Is it then possible for me to include this code in my SQL insert command? 那么我可以在我的SQL插入命令中包含此代码吗? '$date = '01/24/2006'; $date = date('Ym-d', strtotime($date)); $sql = "INSERT INTO table SET date = '$date'";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM