5

I want to have a date like new Date().toISOString() of javascript

The output is 2018-06-11T08:30:25.597Z

I tried with

(new \DateTime('now',new \DateTimeZone("UTC")))->format(\DateTime::ISO8601) // 2018-06-12T08:21:13+0000


$t = date('c', strtotime('2010-12-30 23:21:46')); //2010-12-30T23:21:46+01:00
$t2 = date(DATE_ISO8601, strtotime('2010-12-30 23:21:46')); //2010-12-30T23:21:46+01:00

$datetime = new \DateTime('2010-12-30 23:21:46');
$t3 = $datetime->format(\DateTime::ATOM); // 2010-12-30T23:21:46+01:00

I want to combine

Combined ISO 8601 date and time in UTC (YYYY-MM-DDTHH:MM:S+Timezone Offset|Z, i.e., 2018-04-18T11:02:05.261Z)

In Javascript I can have this format with

new Date().toISOString() //2018-06-12T08:24:49.321Z
monkeyUser
  • 4,301
  • 7
  • 46
  • 95

1 Answers1

1

Your first try is almost what you need, just change \DateTime::ISO8601 to \DateTime::ATOM.

From PHP manual:

DateTime::ISO8601 DATE_ISO8601

ISO-8601 (example: 2005-08-15T15:52:01+0000)

Note: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use DateTime::ATOM or DATE_ATOM for compatibility with ISO-8601 instead.

Łukasz Jakubek
  • 995
  • 5
  • 12
  • 2
    with `(new \DateTime('now',new \DateTimeZone("UTC")))->format(\DateTime::ATOM);` I have `2018-06-12T08:37:38+00:00` But I want `2018-06-11T08:30:25.597Z` – monkeyUser Jun 12 '18 at 08:40
  • 1
    If you need "Z" as timezone identifier, there is no way, just `str_relpace( "+00:00", "Z", $date);` PHP haven't "Z" timezone identifier format. If you need fraction of second, then starting from `PHP 7.0` you can use `\DateTime::RFC3339_EXTENDED` or format string: `Y-m-d\TH:i:s.vP` in any PHP version. – Łukasz Jakubek Jun 12 '18 at 08:50
  • 1
    `$a = (new \DateTime('now',new \DateTimeZone("UTC")))->format(\DateTime::ATOM); $b = str_replace( "+00:00", "Z", $a); // 2018-06-12T08:53:02Z` – monkeyUser Jun 12 '18 at 08:53
  • 2
    @monkeyUser: there is a simpler solution: `echo (new \DateTime('UTC'))->format('Y-m-d\TH:i:s\Z');` – Glavić Jun 12 '18 at 11:25