1

I have an object that has a property that is a DateTime object that has a set timezone depending on the user's timezone. At some point I need to store the object where in my storage layer the property is a UTC datetime string, however I may need to continue using the object after it has been persisted and currently my approach converts the object to another timezone and then sets it back to what it used to be:

/* "starts" is the name of the property and this is just a "magic" method my driver
    will call before persisting the object. */

public function __persist_starts() {
    $tz = $this->starts->getTimezone();
    $this->starts->setTimezone(new DateTimeZone("UTC"));
    $value = $this->starts->format('Y-m-d H:i:s');
    $this->starts->setTimezone($tz);
    return $value;
}

This appears to be a "hacky" solution, isn't there something clearer I can use. I'm imagining something like

public function __persist_starts() {
    return $this->starts->formatUTC('Y-m-d H:i:s');
}
3
  • You can always write your own class extending DateTime that includes a new method with that formatUTC() code, in the same way Carbon extends DateTime and provides a series of built-in methods for different formats Commented May 26, 2016 at 11:21
  • @MarkBaker yeah but I'm surprised the guys at php didn't provide this functionality, there must be a good reason for that? Commented May 26, 2016 at 11:22
  • A good reason? They didn't think it needed to be explicitly provided when it can easily be done in userland code, perhaps? Commented May 26, 2016 at 11:23

1 Answer 1

2

Although there is nothing like formatUTC, there are few other options, slightly better than the "hacky" solution:

  • if you have such luxury, use DateTimeImmutable instead of DateTime.
  • clone the original object:

    public function __persist_starts() {
        $utc = clone $this->starts;
        return $utc->setTimezone(new \DateTimeZone("UTC"))
                   ->format('Y-m-d H:i:s');
    }
    
  • create a new object:

    public function __persist_starts() {
        return \DateTime::createFromFormat(
            'U', 
            $this->starts->getTimestamp(), 
            new \DateTimeZone("UTC")
        )->format('Y-m-d H:i:s');
    }
    
Sign up to request clarification or add additional context in comments.

Comments

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.