PHP datetime子问题 [英] PHP datetime sub issue

查看:64
本文介绍了PHP datetime子问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$currentDT = new \DateTime(); 
$filterRange = new \DateInterval('PT30S'); 
$filterDate = $currentDT->sub($filterRange); 
var_dump($currentDT); 
var_dump($filterDate);

输出:

object(DateTime)[246]
  public 'date' => string '2011-12-10 15:53:42' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/New_York' (length=16)
object(DateTime)[246]
  public 'date' => string '2011-12-10 15:53:42' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'America/New_York' (length=16)

$ currentDT和$ filterDate相同。 。即使它们应该相差30多岁。知道为什么吗?

$currentDT and $filterDate are the same...even though they should be 30s different. Any idea why?

推荐答案

这是预期的行为,减法作用于原始对象,然后将其返回。这可以通过 var_dump()输出中的 246 看到,表明它们是一个相同的对象。

That is the expected behaviour, the subtraction acts on the original object which is then returned. This can be seen by the 246 in the var_dump() outputs, denoting that they're one and the same object.

如果您希望保持原始对象不变,则需要 克隆 ,然后再进行减法。

If you wish to keep the original object untouched, you'll need to clone it before doing the subtraction.

$currentDT   = new \DateTime('2011-12-13 14:15:16');
$filterRange = new \DateInterval('PT30S');
$filterDate  = clone $currentDT;
$filterDate->sub($filterRange);
var_dump($currentDT, $filterDate);

这篇关于PHP datetime子问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆