繁体   English   中英

PHP UTC 字符串到日期

[英]PHP UTC String to date

我有个问题。 在我的代码中,我有以下行:

$RunDateTimeGMT0 = "2017-12-31 23:00:00";

目标是获得前一小时和下一小时,所以我尝试了这个:

$RunDateTimeGMT0 = "2017-12-31 23:00:00";
$epochRunDateTimeGMT0 = strtotime($RunDateTimeGMT0);
$previousEpochDateTimeGMT0 = $epochRunDateTimeGMT0 - 3600;
$nextEpochDateTimeGMT0 = $epochRunDateTimeGMT0 + 3600;

但后来我得到以下结果:

previousEpochDateTimeGMT0 -> 2017-12-31 21:00:00
nextEpochDateTimeGMT0 -> 2017-12-31 23:00:00

由于我的时区(+1)RunDateTimeGMT0被转换为我的时区的日期。 我想要以下结果:

validEpochDateTimeGMT0 -> 2017-12-31 22:00:00
nextEpochDateTimeGMT0 -> 2018-01-01 00:00:00

如何保留日期 object UTC?

您可以使用Carbon库。 导入此库后,您应该使用以下方法解析日期:

$RunDateTimeGMT0 = "2017-12-31 23:00:00";
$epochRunDateTimeGMT0 = Carbon::parse($RunDateTimeGMT0);

这个链接中,你可以看到 Carbon 的文档。 虽然,也许你应该使用这种方法:

$previousEpochDateTimeGMT0 = $epochRunDateTimeGMT0->addminutes(60);
$nextEpochDateTimeGMT0 = $epochRunDateTimeGMT0->subminutes(60);

我希望您的问题可以通过这些行解决,如果发生其他问题,您可以询问。

@Ebrahim Bashirpour 已经通过使用 Carbon 库共享了一种执行此操作的方法,但您也可以仅使用 PHP 日期时间 class 来执行此操作。 它支持以秒为单位的加法减法 查看 DateTime文档以获取更多详细信息。

<?php
    $RunDateTimeGMT0 = "2017-12-31 23:00:00";

    $date = new \DateTime($RunDateTimeGMT0);
    $date->add(new \DateInterval('PT3600S')); //add 3600s / 1 hour
    $next_epoc = $date->format('Y-m-d H:i:s'); // 2018-01-01 00:00:00


    $date = new \DateTime($RunDateTimeGMT0);
    $date->sub(new \DateInterval('PT3600S'));//add 3600s / 1 hour
    $previous_epoc = $date->format('Y-m-d H:i:s'); //2017-12-31 22:00:00

    var_dump($next_epoc);
    var_dump($previous_epoc);
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM