7

I'm getting dates from feed in this format:

2009-11-04T19:55:41Z

I'm trying to format it using the date() function in PHP, but I get an error saying:

date() expects parameter 2 to be long, object given in /bla/bla.php

I tried using preg_replace() to remove the T and the Z, but still can't get it to work.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
Yaniv Golan
  • 982
  • 5
  • 15
  • 28

5 Answers5

16

strtotime is a wonderful function for converting date formats to Unix timestamps.

This will give you what you're after:

date('my format here', strtotime('2009-11-04T19:55:41Z'));
Josh Leitzel
  • 15,089
  • 13
  • 59
  • 76
  • 1
    Remember that `strtotime` uses the timezone it can find (for example in the `TZ` environment variable. The function documentation fails to give any pointers on what happens to timestamps that embed the time zone information. – Joey Nov 04 '09 at 23:30
13

What about

\DateTime::createFromFormat(\DateTime::ATOM, $AtomDate); // converting Atom date to object

or

date(\DateTime::ATOM, $timestamp); // formatting timestamp to Atom time

or both

$dto = \DateTime::createFromFormat(\DateTime::ATOM, $AtomDate);
date('d-M-Y H:i:s', $dto->getTimestamp()); // formatting Atom date to anything you want

or even better

$dto = \DateTime::createFromFormat(\DateTime::ATOM, $AtomDate);
$formattedDate = $dto->format('d-M-Y H:i:s');

or with time zone (as mentioned in comments)

$dto = \DateTime::createFromFormat(
    \DateTime::ATOM,
    $ticketUpdatedAt,
    new \DateTimeZone('UTC')
);
$ticketUpdatedDate = $dto->format('Y-m-d H:i:s');
Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
2

Try using strptime:

$date = strptime($str, "Y-m-d\TH:i:s\Z");
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
1

You can use the strtotime function.

echo date('Y-M-D', strtotime($feedDate));
Brian Fisher
  • 23,519
  • 15
  • 78
  • 82
1

That is the standard ISO 8601 combined date and time format given in UTC (hence the Z).

You might be able to parse it using

DateTime::createFromFormat('c', '2009-02-03');

or, if that fails (shouldn't, if PHP claims to understand ISO 8601), you can replace the Z by "+00:00".

Joey
  • 344,408
  • 85
  • 689
  • 683