简体   繁体   English

如何在PHP中添加一分钟到DateTime()对象?

[英]How can I add one minute to a DateTime() object in PHP?

I am trying to make a time interval: $start to $end . 我想做一个时间间隔: $start to $end But $start is always ending up the same as $end , as if they are both getting modified. $start总是与$end ,好像它们都被修改了。

$dt = new \DateTime();
$start = $dt;
$end = $dt->modify('+1 minute');
echo $start->format('i') . ' - ' . $end->format('i');

This just gave me 这只是给了我

50 - 50 50 - 50

When I want 当我想要的时候

49 - 50 49 - 50

What am I doing wrong? 我究竟做错了什么?

Edit: I don't want to work with timestamps, only DateTime() objects. 编辑:我不想使用时间戳,只有DateTime()对象。

Why this is happening 为什么会这样

$start and $end both refer to the same object so when you add 1 minute to $dt both $start and $end will reflect the change. $start$end都引用同一个对象,所以当你向$dt添加1分钟时, $start$end都会反映出这一变化。

What can you do 你能做什么

To fix, set $start and $end to new instances of the datetime object. 要修复,请将$start$end设置$start datetime对象的新实例。

$dt = new \DateTime();
$start = new $dt;
$end = new $dt;
$end->modify('+1 minute');
echo $start->format('i') . ' - ' . $end->format('i');

An alternative to the already given answers would be to use 已经给出的答案的替代方案是使用

  • DateTimeImmutable - This class behaves the same as DateTime except it never modifies itself but returns a new object instead. DateTimeImmutable - 此类的行为与DateTime相同,只是它从不修改自身,而是返回一个新对象。

Example: 例:

$start = new \DateTimeImmutable();
$end = $start->modify('+1 minute');
echo $start->format('i') . ' - ' . $end->format('i');

This would give your expected result. 这将给出您的预期结果。

You create a single DateTime object $dt and then use the same object as both $start and $end . 您创建一个DateTime对象$dt然后使用相同的对象作为$start$end You should do one of the following: 您应该执行以下操作之一:

$dt = new \DateTime();
$start = $dt->format('i'); //Store the actual string before modifying
$dt->modify('+1 minute'); 
echo $start . ' - ' . $end->format('i');

Or: 要么:

$start = new \DateTime();
$end = new \DateTime();    
$end->modify('+1 minute'); 
echo $start->format('i') . ' - ' . $end->format('i');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM