简体   繁体   English

PHP UTC 字符串到日期

[英]PHP UTC String to date

I have a problem.我有个问题。 In my code I have the following line:在我的代码中,我有以下行:

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

The goal is to get the previous and next hour, so I tried this:目标是获得前一小时和下一小时,所以我尝试了这个:

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

But then the I get the following result:但后来我得到以下结果:

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

Because of my timezone (+1) the RunDateTimeGMT0 gets converted to a date of my timezone.由于我的时区(+1)RunDateTimeGMT0被转换为我的时区的日期。 I want the following result:我想要以下结果:

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

How can I keep the date object UTC?如何保留日期 object UTC?

You can use the Carbon library.您可以使用Carbon库。 after import this library you should parse the date with this:导入此库后,您应该使用以下方法解析日期:

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

in this link , you could see the documentation of Carbon.这个链接中,你可以看到 Carbon 的文档。 Although, maybe you should to use this method:虽然,也许你应该使用这种方法:

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

I hope your problem solve with these lines, If another issue occurred you can ask.我希望您的问题可以通过这些行解决,如果发生其他问题,您可以询问。

@Ebrahim Bashirpour already shared a way of doing this by using the Carbon library but you can also do this by just using the PHP Datetime class. @Ebrahim Bashirpour 已经通过使用 Carbon 库共享了一种执行此操作的方法,但您也可以仅使用 PHP 日期时间 class 来执行此操作。 It supports both add time and subtracts time in seconds.它支持以秒为单位的加法减法 Take a look at the DateTime documentation for more details.查看 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