我正在尝试制作一个时间间隔:$start
到$end
。但是$start
总是和$end
一样,好像它们都被修改了。
$dt = new 'DateTime();
$start = $dt;
$end = $dt->modify('+1 minute');
echo $start->format('i') . ' - ' . $end->format('i');
这给了我
50 - 50
当我想
49 - 50
我做错了什么?
编辑:我不想使用时间戳,只使用DateTime()对象。
为什么会这样
$start
和$end
都指向同一个对象,所以当你给$dt
增加1分钟时,$start
和$end
都会反映这个变化。
你能做什么
修复,设置$start
和$end
为datetime对象的新实例。
$dt = new 'DateTime();
$start = new $dt;
$end = new $dt;
$end->modify('+1 minute');
echo $start->format('i') . ' - ' . $end->format('i');
对于已经给出的答案,可以使用
-
DateTimeImmutable
-这个类的行为与DateTime相同,除了它从不修改自己,而是返回一个新对象。
的例子:
$start = new 'DateTimeImmutable();
$end = $start->modify('+1 minute');
echo $start->format('i') . ' - ' . $end->format('i');
这将给出您期望的结果。
创建单个DateTime对象$dt
,然后将其作为$start
和$end
使用。您应该执行以下操作之一:
$dt = new 'DateTime();
$start = $dt->format('i'); //Store the actual string before modifying
$dt->modify('+1 minute');
echo $start . ' - ' . $end->format('i');
或:
$start = new 'DateTime();
$end = new 'DateTime();
$end->modify('+1 minute');
echo $start->format('i') . ' - ' . $end->format('i');