php - 使用数据库中的 DateTime() 格式化部分未知日期?

标签 php mysql

我有一个数据库,其中有一些未知的月份或日期格式如下:1999-01-00/1999-00-00 .

现在,我一直在使用 DateTime()格式化已满的日子,效果很好。

我想使用 $DateTime->format('M Y'); 来表示未知日期和已知月份的缩写输出 Sep 1999

$DateTime->format('Y');对于 1999那是未知的月份和日期。

DateTime()不允许 00月/天的值,那么有什么方法可以解决这个问题?

最佳答案

正是我要找的(但不想听)。

这是一个基本的 php 函数,适合像我这样懒惰的人。

function formatDatabaseDate($date, $delimiter = '/')
{
    // this function works only on mysql date fields, 
    // and takes into account partial dates.
    if ($date != '' && $date != NULL)
    {
        $datePieces = explode('-', $date);
        if (count($datePieces) == 3 && 
            strlen($datePieces[0]) == 4 && 
            strlen($datePieces[1]) == 2 && 
            strlen($datePieces[2]) == 2)
        {
            $datestring = '';

            $months['01'] = 'Jan';
            $months['02'] = 'Feb';
            $months['03'] = 'Mar';
            $months['04'] = 'Apr';
            $months['05'] = 'May';
            $months['06'] = 'Jun';
            $months['07'] = 'Jul';
            $months['08'] = 'Aug';
            $months['09'] = 'Sep';
            $months['10'] = 'Oct';
            $months['11'] = 'Nov';
            $months['12'] = 'Dec';

            if ($datePieces[2] != '00' && $datePieces[1] != '00')
            {
                $datestring = $datePieces[2] . $delimiter 
                            . $months[$datePieces[1]] . $delimiter 
                            . $datePieces[0];
            }
            else if ($datePieces[1] != '00')
            {
                $datestring = $months[$datePieces[1]] . $delimiter 
                            . $datePieces[0];
            }
            else
            {
                $datestring = $datePieces[0];
            }

            return $datestring;

        }
        else
        {
            trigger_error('date is not in a valid mysql format');
            return false;
        }
    }
    else
    {
        trigger_error('empty date passed to format command');
        return false;
    }
}

关于php - 使用数据库中的 DateTime() 格式化部分未知日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10560108/

相关文章:

php - 在 PHP 中使用 '<' 比较两个对象

java - 签名问题 --- openssl_sign

php - 如何创建百分比图像

javascript - 日期选择器未将所选日期保存到 mysql

mysql - JOIN mysql 表上的 PRIMARY KEY 和 JSON 数组

php - 使用 AJAX 将复选框值(如果未选中则为 0)传递给 PHP

php - PHP 中的 foreach 字符串

php - 在 PHP 中用等号和逗号分割字符串的最佳方法是什么

mysql - LOAD DATA LOCAL INFILE 语法错误

Mysql,用另一个表列替换整个列