【问题标题】:Modify DateTimeImmutable with input value使用输入值修改 DateTimeImmutable
【发布时间】:2019-10-24 15:47:41
【问题描述】:

我需要用表单中的输入值修改“+1 月”。

现在,我有这样的

public function buy($userId, ProductForm $form): void
    {

        $user = $this->users->get($userId);
        $product = $this->products->get($form->productId);

        $user->addOrder(
            $now->format('Y-m-d H:i:s'),
            $now->modify('+1 month')->format('Y-m-d H:i:s')
        );

        $this->users->save($user);
    }

    In ProductForm 

      public function periodList(): array
    {
        return [
            '+1 month' => '1 Month',
            '+2 month' => '2 Month',
            '+3 month' => '3 Month',
        ];
    }

我尝试获取 $now + 表单值的日期,可以是 1 到 3 个月。

感谢您的帮助。

【问题讨论】:

  • 请向我们展示更多代码。您在哪里访问修改后的值并看到它不正确。 addOrder 有什么作用?更多详细信息和代码将使我们能够更好地帮助您
  • 我已经更新了代码。只需添加到 $now + 表单周期。

标签: php forms datetime input


【解决方案1】:

你试过了吗:

$now = new \DateTimeImmutable();

$formattedPlusAMonth = $now->modify('+1 month')->format('Y-m-d H:i:s')

您应该阅读 DateTimeImmutable 类。它从不修改源(这就是它被称为不可变的原因)。您需要在新变量中捕获它返回的内容。

https://www.php.net/manual/en/class.datetimeimmutable.php

【讨论】:

  • 你是对的,它表明它永远不会修改,初学者错误。现在,我有这样的 $now = new \DateTimeImmutable(); $now->modify('+1 月')->format('Y-m-d H:i:s') 尝试获取$now+form值的日期,可以是1到3个月。
  • 使用最新代码更新您的原始问题。另外,我仍然看不到您在上次评论中分配新值的位置
猜你喜欢
  • 1970-01-01
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
相关资源
最近更新 更多