在我的脚本中,我想获得今天的月份和上个月,所以我这样做:
date_default_timezone_set('UTC');
$month = date('Ym');
$lastmonth = date('Ym', strtotime('first day of -1 month');
这有多安全?是否有可能在第二行和第三行之间,时间发生了变化(新的一个月开始),因此它两次返回同一个月份?我知道可能性很小,但我正在处理一个可能有如此多交易的系统。
我认为一个安全的选择是:
date_default_timezone_set('UTC');
$dt = new DateTime();
$month = $dt->format('Ym');
$dt2 = $dt; // to save $dt for later use
$lastmonth = $dt2->modify('first day of -1 month')->format('Ym');
但这真的有必要还是有更好的方法?
正如@silkfire 评论的那样,您的第二个示例已经是最安全/首选的方法。但是,有一些事情/提示需要解释。
首先,正如@MateiMihai 所提到的,您正在另一个变量中复制/保存一个对象。在这种情况下,您应该使用 clone 而不是引用副本:
$dt = clone $dt;
你的代码将是:
date_default_timezone_set('UTC');
$dt = new DateTime();
$month = $dt->format('Ym');
$dt2 = clone $dt; // to save $dt for later use
$lastmonth = $dt2->modify('first day of -1 month')->format('Ym');
此外,如果您必须保留原始对象,您应该使用DateTimeImmutable
并调整您的代码(不需要$dt2
变量)
date_default_timezone_set('UTC');
$dt = new DateTimeImmutable();
$month = $dt->format('Ym');
$lastmonth = $dt->modify('first day of -1 month');//It's a new object with the new date
echo $lastmonth->format('Ym');
另外,就个人意见而言,我更喜欢“可读性更好”的方法,因为:
$dt->modify('first day of last month');
结果完全一样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句