【问题标题】:DateTime data type, MySQL and YiiDateTime 数据类型,MySQL 和 Yii
【发布时间】:2015-02-27 12:31:36
【问题描述】:

假设我在 MySQL 中有一个表,其字段类型为 DateTime。让我们将该字段称为fa

现在假设我在 Yii 1 (1.1.16) 中有以下代码:

$model = MyTable->createNewModel(); // <-- pseudo code
$model->fa = new DateTime("now");
$model->save();

$model = MyTable->getByPk(1); // <-- pseudo code
$model->fa; // <-- question 1
$model->fa = $model->fa->modify("+1 month"); // <-- question 2
$model->save();

我有以下问题:

问题一:

变量$model-&gt;fa 是什么类型(在注释为“问题1”的那一行)?它是一个字符串吗?它是 PHP 的 DateTime 类型吗?还是 DateTime 的某种 Yii 表示?

问题2:

如果我之前的问题的答案是“PHP 的 DateTime 类型”,那么带有“问题 2”的注释的那一行是完全有效的,应该不会有任何问题。但是$model-&gt;fa 的类型不是 PHP 的 DateTime 类型吗?我如何将 1 个月添加到 $model-&gt;fa

另外请注意,我知道我可以随意使用format 并制作一个丑陋的解决方案,其中涉及从/到我自己的日期/时间格式表示的解析,但如果可能的话,我想避免这种情况。

【问题讨论】:

  • 您是否尝试过使用var_dump($model) 来确定所有属性的数据类型?
  • 这是 PHP 问题,不是 yii 问题,请编辑您的标签。

标签: php mysql datetime yii


【解决方案1】:

第一季度: 是的,它必须是 DateTime 类型。

第二季度: 您可以使用此函数为您的 dateTime 变量添加一个月。

function addMonth($iDate,$num = 1)
{
    $date = $iDate->format('Y-n-j');
    list($y, $m, $d) = explode('-', $date);

    $m += $num;
    while ($m > 12)
    {
        $m -= 12;
        $y++;
    }

    $last_day = date('t', strtotime("$y-$m-1"));
    if ($d > $last_day)
    {
        $d = $last_day;
    }


    $fDate = new DateTime();
    return $fDate->setDate($y, $m, $d);
}

【讨论】:

  • 如果fa是DateTime类型,我其实可以使用modify方法(php.net/manual/es/datetime.modify.php)。
  • 是的,你可以使用它,但对我来说,我不想在 2014-10-31 日期的 2014-12-01 结果。我使用这个功能只是因为它。
猜你喜欢
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
相关资源
最近更新 更多