我有一个数据库,其中有一些未知的月份或日期格式如下: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/