DateTime数据类型,MySQL和Yii

时间:2021-10-05 16:12:09

Let's pretend I have a table in MySQL with a field of the type DateTime. Let's call that field fa.

让我假装我在MySQL中有一个表,其中包含DateTime类型的字段。我们称那个领域为fa。

Now let's pretend I have the following code in Yii 1 (1.1.16):

现在让我假装我在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();

I have the following questions:

我有以下问题:

Question 1:

What type is the variable $model->fa (at the line with the comment that says 'question 1')? Is it a string? Is it a PHP's DateTime type? Or is it some sort of Yii representation of DateTime?

变量$ model-> fa是什么类型(在带有'问题1'的注释的行上)?它是一个字符串?它是PHP的DateTime类型吗?或者它是DateTime的某种Yii表示?

Question 2:

If the anwers of my previous question is "PHP's DateTime type", then the line with the comment that says "question 2" is perfectly valid, and there shouldn't be any problems with it. But what is the type of $model->fa isn't PHP's DateTime type? How would I add 1 month to $model->fa?

如果我之前的问题的答案是“PHP的日期时间类型”,那么带有“问题2”的评论的行是完全有效的,并且不应该有任何问题。但是$ model-> fa的类型是不是PHP的DateTime类型?我如何将1个月添加到$ model-> fa?

Also please note that I know I could just hack around with format and make an ugly solution that involves parsing from/to my own format representation of date/time, but I'd like to avoid that if possible.

另请注意,我知道我可以解决格式问题并制作一个丑陋的解决方案,涉及从/向我自己的日期/时间格式表示解析,但我想尽可能避免这种情况。

1 个解决方案

#1


0  

Q1 : Yes it must be in DateTime type.

Q1:是的,它必须是DateTime类型。

Q2 : You can use this function to add one month to your dateTime variable.

Q2:您可以使用此功能为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);
}

#1


0  

Q1 : Yes it must be in DateTime type.

Q1:是的,它必须是DateTime类型。

Q2 : You can use this function to add one month to your dateTime variable.

Q2:您可以使用此功能为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);
}