PHP日期时间子问题
输出:PHP日期时间子问题,php,datetime,Php,Datetime,输出: $currentDT = new \DateTime(); $filterRange = new \DateInterval('PT30S'); $filterDate = $currentDT->sub($filterRange); var_dump($currentDT); var_dump($filterDate); $currentDT和$filterDate是相同的…尽管它们应该是30秒不同。知道为什么吗?DateTime::sub更改当前对象中的日期,并返回其
$currentDT = new \DateTime();
$filterRange = new \DateInterval('PT30S');
$filterDate = $currentDT->sub($filterRange);
var_dump($currentDT);
var_dump($filterDate);
$currentDT和$filterDate是相同的…尽管它们应该是30秒不同。知道为什么吗?DateTime::sub更改当前对象中的日期,并返回其副本以进行方法链接。因此,在您的示例中,您正在更改两个对象的日期,因此这两个对象都将设置为30秒前
尝试此操作-它使用两个单独初始化的对象进行比较:
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)
或者,正如@salathe所指出的,当然可以使用clone关键字。DateTime::sub更改当前对象中的日期,并返回其副本以进行方法链接。因此,在您的示例中,您正在更改两个对象的日期,因此这两个对象都将设置为30秒前
尝试此操作-它使用两个单独初始化的对象进行比较:
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)
或者,正如@salathe所指出的,当然要使用clone关键字。这是预期的行为,减法作用于原始对象,然后返回。这可以从var_dump输出中的246中看出,这表示它们是同一个对象 如果您希望保持原始对象不变,则需要在执行减法运算之前对其进行修改
$current1 = new \DateTime();
$current2 = new \DateTime();
$filterRange = new \DateInterval('PT30S');
$current2->sub($filterRange);
var_dump($current1); // Should return the current time
var_dump($current2); // Should return the current time - 30 seconds
这是预期的行为,减法作用于原始对象,然后返回。这可以从var_dump输出中的246中看出,这表示它们是同一个对象 如果您希望保持原始对象不变,则需要在执行减法运算之前对其进行修改
$current1 = new \DateTime();
$current2 = new \DateTime();
$filterRange = new \DateInterval('PT30S');
$current2->sub($filterRange);
var_dump($current1); // Should return the current time
var_dump($current2); // Should return the current time - 30 seconds
唯一的方法是克隆,而不是创建两个连续的datetime实例,因为instance1和instance2可能不相等,这取决于服务器的处理速度 唯一的方法是克隆,而不是创建两个连续的datetime实例,因为instance1和instance2可能不相等,这取决于服务器的处理速度