1<?php
2
3namespace IXR\DataType;
4
5/**
6 * IXR_Date
7 *
8 * @package IXR
9 * @since 1.5.0
10 */
11class Date
12{
13    /** @var \DateTime */
14    private $dateTime;
15
16    public function __construct($time)
17    {
18        // $time can be a PHP timestamp or an ISO one
19        if (is_numeric($time)) {
20            $this->parseTimestamp($time);
21        } else {
22            $this->parseIso($time);
23        }
24    }
25
26    private function parseTimestamp($timestamp)
27    {
28        $date = new \DateTime();
29        $this->dateTime = $date->setTimestamp($timestamp);
30    }
31
32    /**
33     * Parses more or less complete iso dates and much more, if no timezone given assumes UTC
34     *
35     * @param string $iso
36     * @throws \Exception when no valid date is given
37     */
38    protected function parseIso($iso) {
39        $this->dateTime = new \DateTime($iso, new \DateTimeZone('UTC'));
40    }
41
42    public function getIso()
43    {
44        return $this->dateTime->format(\DateTime::ATOM);
45    }
46
47    public function getXml()
48    {
49        return '<dateTime.iso8601>' . $this->getIso() . '</dateTime.iso8601>';
50    }
51
52    public function getTimestamp()
53    {
54        return (int)$this->dateTime->format('U');
55    }
56}
57