我想在特定时区获取当前日期的昨天日期。 我试过这样,但它不起作用:
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$yesterday = $date->modify( '-1 day' );
$yesterday = $yesterday->format('Y-m-d');
我今天还在约会。
答案 0 :(得分:4)
根据documentation for the modify()
method,这个问题似乎完全取决于您使用的是哪个版本的php。在这种情况下,根据之前链接的文档中的changelog,方法链(这是您尝试执行的操作)仅在php 5.3.0及更高版本上可用。
考虑到这一点,它解释了为什么你的代码不起作用,而@ Deryck做了。如果你升级了你的php版本,或者让你的主机升级它,你可能会将这三行减少到两行:
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date = $date->modify( '-1 day' )->format('Y-m-d');
我意识到,并没有太大的改进,但是你知道它失败的原因。
以下是我看到的解决这个问题的两种方法;一个是类的创造..这对我来说似乎有点过分,除非这是一个更宏大的东西...另一个是功能的创造。在某种意义上,两者都将额外的线条推到了占用更少空间的东西上。
class DT {
private $now; //can be null
private $timezone; //DateTimeZone object
public function __construct($tz_str, $now = NULL) {
$this->now = $now;
$this->timezone = new DateTimeZone($tz_str);;
}
public function mod($mod,$format) {
$dt = new DateTime($this->now, $this->timezone);
$dt->modify($mod);
return $dt->format($format);
}
}
function mod_formatted_zone($tz_str, $mod, $format, $now = NULL) {
$timezone = new DateTimeZone($tz_str);
$dt = new DateTime($now,$timezone);
$dt->modify($mod);
return $dt->format($format);
}
使用任何一种都很简单;在课堂上,它就像是......
$dt = new DT('Pacific/Wake');
echo $dt->mod('-1 day', 'Y-m-d');
在功能的情况下,它只是... ..
echo mod_formatted_zone('Pacific/Wake', '-1 day', 'Y-m-d');
答案 1 :(得分:2)
一旦您不必要地重新分配$date
变量,似乎工作正常。见下文:
<?php
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date->modify("-1 day");
$date = $date->format("Y-m-d");
// echo $date; // just in case you wanna echo - ya dig
?>
<强>供参考:强>
威克岛时区(UTC + 12:00)
这意味着前一天实际上今天(至少对我而言,在西半球)。
答案 2 :(得分:0)
我想在特定时区获取当前日期的昨天日期。
您可以在DateTime构造函数中指定相对日期。这对你有用: -
$yesterday = new DateTime('- 1 day', new DateTimeZone('Pacific/Wake'));
var_dump($yesterday);