xref: /aosp_15_r20/external/protobuf/php/src/Google/Protobuf/Internal/TimestampBase.php (revision 1b3f573f81763fcece89efc2b6a5209149e44ab8)
1<?php
2
3namespace Google\Protobuf\Internal;
4
5/**
6 * Base class for Google\Protobuf\Timestamp, this contains hand-written
7 * convenience methods.
8 */
9class TimestampBase extends \Google\Protobuf\Internal\Message
10{
11    /*
12     * Converts PHP DateTime to Timestamp.
13     *
14     * @param \DateTime $datetime
15     */
16    public function fromDateTime(\DateTime $datetime)
17    {
18        $this->seconds = $datetime->getTimestamp();
19        $this->nanos = 1000 * $datetime->format('u');
20    }
21
22    /**
23     * Converts Timestamp to PHP DateTime.
24     *
25     * @return \DateTime $datetime
26     */
27    public function toDateTime()
28    {
29        $time = sprintf('%s.%06d', $this->seconds, $this->nanos / 1000);
30        return \DateTime::createFromFormat('U.u', $time);
31    }
32}
33