2

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. 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?

2
  • use date_default_timezone_set('UTC') Commented Feb 14, 2021 at 21:03
  • 1
    You're not showing how you go from a timestamp to a readable date. And the ), after the 3600, must cause an error message? Commented Feb 14, 2021 at 21:05

2 Answers 2

2

You can use the Carbon library. 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. 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.

Sign up to request clarification or add additional context in comments.

Comments

1

@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. It supports both add time and subtracts time in seconds. Take a look at the DateTime documentation for more details.

<?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);
?>

1 Comment

yeah, we could use raw PHP Datetime class. But I prefer Cabon for more options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.