11

I have a year (2002) and I'm trying to get it into the following format:

2002-00-00T00:00:00

I tried various iterations, the last of which was this:

$testdate = DateTime::createFromFormat(DateTime::ISO8601, date("c"))
echo date_format($testdate, '2002'); 

But, even if I come close, it always seems to add +00:00 to the end of it...

KumbaThought
  • 183
  • 2
  • 3
  • 10

4 Answers4

17

The 'c' format in PHP always appends the timezone offset. You can't avoid that. But you can build the date yourself from components:

date('Y-m-d\TH:i:s', $testdate);
Marc B
  • 356,200
  • 43
  • 426
  • 500
6

Best way is to use constants (PHP 5 >= 5.5.0, PHP 7)

date(DATE_ISO8601, $timeToChange);

Docs: http://php.net/manual/en/class.datetimeinterface.php#datetime.constants.types

fearis
  • 424
  • 3
  • 15
  • `DATE_ISO8601` also adds the `+00:00` timezone bit OP is trying to avoid. Example: `echo date(DATE_ISO8601, 1612308970); // prints "2021-02-02T23:36:10+0000"` – kaldimar Feb 02 '21 at 23:34
  • Create new constant and use it like in example as this should be reusable and easy to read - as per link which I've sent. define("DATE_ISO8601_WITHOUT_TIME", "Y-m-d\TH:i:s"); date(DATE_ISO8601_WITHOUT_TIME, $timeToChange); – fearis Mar 10 '21 at 11:46
3

The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:

// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z

// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z

// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z

//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

Previous published: https://stackoverflow.com/a/61796705/5898408

Clary
  • 544
  • 1
  • 7
  • 8
2
date('Y-m-d\TH:i:s\Z', time() - date('Z'));
Frank
  • 21
  • 2
  • 5
    elaborate more for better explanation – Rumit Patel Feb 27 '18 at 06:39
  • 1
    Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Feb 27 '18 at 12:47