php datetime / datetimezone减去2小时而不是1小时

时间:2013-01-15 21:01:35

标签: php datetime timezone

您好我有一个特殊的时区,如欧洲/柏林,我想在当前日期添加90天。之后我发现了一个月的最后一天。

数据库中的我的日期以UTC格式保存。这就是为什么我必须在最后改变时区。

我的问题是,时区变化从欧洲/柏林和UTC之间的时间减去2小时。如果我在更改日期时间对象之前将其更改为UTC,那么它将减去1小时。任何人都可以告诉我问题是什么或正确的解决方案吗?

//$timezone = 'Europe/Berlin';
private function getMaxTillDate($timezone)
{        
    $threemonth = new \DateTime('now', new \DateTimeZone($timezone) );
    $threemonth->setTime(23, 59, 59);
    $threemonth->add(new \DateInterval('P0Y90DT0H0M'));
    $maxday = $threemonth->format('t');        
    $threemonth->setDate($threemonth->format('Y'), $threemonth->format('m'), $maxday);
    $threemonth->setTimezone(new \DateTimeZone('UTC'));

    return $threemonth;
}

非常感谢

1 个答案:

答案 0 :(得分:0)

我测试了你的代码 - 它对我有用:

function getMaxTillDate($timezone){
    $threemonth = new \DateTime('now', new \DateTimeZone($timezone) );
    var_dump(1, $threemonth);
    $threemonth->setTime(23, 59, 59);
    var_dump(2, $threemonth);
    $threemonth->add(new \DateInterval('P0Y90DT0H0M'));
    var_dump(3, $threemonth);
    $maxday = $threemonth->format('t');
    var_dump(4, $threemonth, $maxday);
    $threemonth->setDate($threemonth->format('Y'), $threemonth->format('m'), $maxday);
    var_dump(5, $threemonth);
    $threemonth->setTimezone(new \DateTimeZone('UTC'));
    var_dump(6, $threemonth);
    return $threemonth;
}

$tz = "Europe/Berlin";

var_dump(getMaxTillDate($tz));

结果:

int(1)
class DateTime#1 (3) {
public $date =>
string(19) "2013-01-15 22:29:59"
public $timezone_type =>
int(3)
public $timezone =>
string(13) "Europe/Berlin"
}
int(2)
class DateTime#1 (3) {
public $date =>
string(19) "2013-01-15 23:59:59"
public $timezone_type =>
int(3)
public $timezone =>
string(13) "Europe/Berlin"
}
int(3)
class DateTime#1 (3) {
public $date =>
string(19) "2013-04-15 23:59:59"
public $timezone_type =>
int(3)
public $timezone =>
string(13) "Europe/Berlin"
}
int(4)
class DateTime#1 (3) {
public $date =>
string(19) "2013-04-15 23:59:59"
public $timezone_type =>
int(3)
public $timezone =>
string(13) "Europe/Berlin"
}
string(2) "30"
int(5)
class DateTime#1 (3) {
public $date =>
string(19) "2013-04-30 23:59:59"
public $timezone_type =>
int(3)
public $timezone =>
string(13) "Europe/Berlin"
}
int(6)
class DateTime#1 (3) {
public $date =>
string(19) "2013-04-30 21:59:59"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
class DateTime#1 (3) {
public $date =>
string(19) "2013-04-30 21:59:59"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}