【问题标题】:DateTime php return a wrong dateDateTime php 返回错误的日期
【发布时间】:2018-11-05 17:07:09
【问题描述】:

我正在使用 PHP DateTime 类为自定义许可系统生成日期。当我调试它时,我注意到日期时间总是错误的,它将是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;
    }
}

【问题讨论】:

    标签: php datetime licensing


    【解决方案1】:

    这是预期的行为,因为您 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

    【讨论】:

    • 它工作得很好,感谢您的回答,我没有考虑到使用DateTime::add() 函数时原始DateTime 对象被修改的事实。我也可以省略时区吧?
    • 是的,您不必指定时区,除非它与服务器时区不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    相关资源
    最近更新 更多