DateTime php return 一个错误的日期

DateTime php return a wrong date

我正在使用 PHP DateTime class 为自定义许可系统生成日期。当我调试它时,我注意到日期时间总是错误的,它将是 5-dec-2018 但现在我们是在 11 月,这个日期对于 expiration_date 也是一样的。

我该如何解决这个问题?我需要将试用期的开始日期增加 30 天。

这是代码。

class Activator {

  private $uuid;
  private $keygen;
  private $licence_code;

  public static function generateLicence($uuid) {

    if (!file_exists(ABSPATH.'/DataStorage/.licence')) {
        $start_date = new DateTime();
        $time_zone = $start_date->setTimezone(new DateTimeZone('Europe/Rome'));
        $trial_date = $start_date->add(new DateInterval('P30D'));
        $end_date = $trial_date->format('d-M-Y');
        $machine_uuid = bin2hex($uuid);
        $licence_code = base64_encode($machine_uuid);

        $licence_file = array(
          'uuid' => $machine_uuid,
          'activation_date' => $time_zone->format('d-M-Y'),
          #'trial_version' => true,
          #'expire_date' => $end_date,
          #'licence_code' => $licence_code
        );

        $w = file_put_contents(ABSPATH.'/DataStorage/.licence', json_encode($licence_file));
        echo $w;
    }
}

这是预期的行为,因为您 add() 到日期(通过执行 $start_date->add(...) - 这修改了原始对象 $start_date

您可以通过几种不同的方式解决此问题,但最简单的方法是创建一个完全在结构中直接添加 30 天的新实例。您还可以将时区设置为 new DateTime().

的第二个参数
$timezone    = new DateTimeZone('Europe/Rome');
$start_date  = new DateTime("now", $timezone);
$trial_date  = new DateTime("+30 days", $timezone);

看到这个live demo