PHP - 处理基督之前和之后的日期

时间:2015-06-26 09:10:04

标签: php datetime

我在我的网站上制作了Biogram,列出了已知的历史人物。

现在,我只是从数据库中获取值,并在许多IF语句中确定要显示的内容。

 /* @var $bio \Models\Library\Biography */
 $birth = [];
 $death = [];
 $date = null;

 if($bio->getBirthMonth() != null) {
    if ($bio->getBirthDay() != null) {
       $birth = [
           $bio->getBirthDay(),
           $bio->getBirthMonth(),
           $bio->getBirthYear(),
       ];
    } else {
       $birth = [
           $bio->getBirthMonth(),
           $bio->getBirthYear(),
       ];
    }
 } else {
    $birth = [
        $bio->getBirthYear(),
    ];
 }

 if($bio->getDeathMonth() != null) {
    if ($bio->getDeathDay() != null) {
       $death = [
           $bio->getDeathDay(),
           $bio->getDeathMonth(),
           $bio->getDeathYear(),
       ];
    } else {
       $death = [
           $bio->getDeathMonth(),
           $bio->getDeathYear(),
       ];
    }
} else {
    $death = [
       $bio->getDeathYear(),
    ];
}

if (!array_filter($birth) && array_filter($death)) {
    $date = 'zm. ' . implode('.', $death);
}
if (array_filter($birth) && !array_filter($death)) {
    $date = 'ur. ' . implode('.', $birth);
}
if (!array_filter($birth) && !array_filter($death)) {
    $date = null;
}
if (array_filter($birth) && array_filter($death)) {
    $date = implode('.', $birth) . ' - ' . implode('.', $death);
}

但首先,我对这种代码不满意(不知道我是否可以写得更好)。

其次当我使用Carbon(例如),并希望从中间年龄显示年份时,它看起来像0552而不是552.

最后一件事是没有"年0"在历史上。基督之后和基督之前有一年。因此,当我想要年级-200时,它会给我-199。

我知道这可以通过在BC上加上-1来处理,但我认为这不是正确的方法。

是否有任何用于DateTime的php库可以很好地处理所有日期?

我也可以,如果是的话;如何重写上面的代码看起来更好?

干杯:)

1 个答案:

答案 0 :(得分:2)

This is a very interesting problem.

Firstly your if statements - I would write a helper function within $bio that contains the logic regarding what to display as your date, making reference to the other properties that exist within $bio. You could call it getPrettyDate() or something like that. That's potentially where your logic for getting the year to display correctly would go too.

After some considerable googling and not much luck, this answer seems to be the most helpful on this subject, certainly some food for thought.

It's also worth noting that using DATE when persisting this information to your database (assuming you're using MySQL, which you may well not be) is probably not the way forward in your case - as noted in that answer, the MySQL definition of DATE is the following

DATE

A date. The supported range is '1000-01-01' to '9999-12-31'.

I have also after writing this just stumbled across this answer which might be the best approach. Good luck!

More reading on ISO-8601 in the context of 'Year 0' here.