How do I convert datetime to ISO 8601 in PHP
Asked Answered
C

11

144

How do I convert my time from 2010-12-30 23:21:46 to ISO 8601 date format? (-_-;)

Croupier answered 16/3, 2011 at 7:38 Comment(5)
@Gordon yes I got about 4,530 results and I found answer from @alexCroupier
@Croupier please point out why none of the 4530 results answered your question.Parrott
@Parrott I'm still learning how to write from A to Z but I found they teach me how to write from Z to A :)Croupier
@Croupier No. They teach you how to write alphabet($from, $to). Almost all of them tell you to use date($format, strtotime($dateString)) or the DateTime object equivalent. They only differ in the input to those functions. All you have to do is go to the correponding pages in the PHP Manual and find out what the input is.Parrott
@Parrott Yes are you correct. I just knew the alphabet and now spelling bee time. Hope I'm in the right school.Croupier
T
287

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601

Procedural

For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));
Trahan answered 16/3, 2011 at 7:42 Comment(14)
Question, the output is 2010-12-30T23:21:46+1100 how to make it to be 2010-12-30T23:21:46+11:00?Croupier
@Croupier Try this preg_replace('/(?<=\d{2})(?=\d{2}$)/', ':', '2010-12-30T23:21:46+1100'). It outputs 2010-12-30T23:21:46+11:00.Trahan
echo date('c', … produces the output with the colon.Parrott
@Parrott Interesting, I never knew that.Trahan
date('c', strtotime('2010-12-30 23:21:46')) nice @Parrott :)Croupier
I would note that using DATE_ISO8601 produces a date string which is slightly different than ISO8601 (the colon is missing in the TZ, ISO8601 expects times to be all with OR all without the colon, not a mixture) - date('c') does produces a strict ISO 8601 valid date - This could cause hard to trace bugs if code expects a strict ISO 8601 datetime format. Ref: en.wikipedia.org/wiki/ISO_8601Emulsifier
@Emulsifier Nowhere does it read that if colons are used to separate the time components, that the timezone designator must follow suit.Lotuseater
DATE_ISO8601 causes problems with JavaScript as ECMAScript Language Specification requires HH:mm ecma-international.org/ecma-262/5.1/#sec-15.9.1.15Adah
@alex, for some reason the constant ISO8601 is not compatible with ISO-8601, use DateTime::ATOM instead, see the note in php.net/manual/en/class.datetime.php#datetime.constants.iso8601Anastomosis
How to remove seconds from the first method. Its giving me output : 2017-03-18T11:30:00+00:00. But I need : 2017-03-18T11:30+00:00.Not
I love this gem from the PHP documentation: "DATE_ISO8601 [...] 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."Readjustment
Keep in mind that strtotime() will convert a date according to the PHP timezone settingHartzog
Note for JetBrains IDE users: ATOM is currently incorrectly marked as removed since PHP 7.2. Bug report: youtrack.jetbrains.com/issue/WI-59894Ginger
It's better to refer to DateTimeInterface::ATOM rather than a child class.Ludwick
M
50

After PHP 5 you can use this: echo date("c"); form ISO 8601 formatted datetime.

http://ideone.com/nD7piL

Note for comments:

Regarding to this, both of these expressions are valid for timezone, for basic format: ±[hh]:[mm], ±[hh][mm], or ±[hh].

But note that, +0X:00 is correct, and +0X00 is incorrect for extended usage. So it's better to use date("c"). A similar discussion here.

Mccray answered 23/6, 2012 at 21:17 Comment(9)
Note the slight difference with DATE_ISO8601; +0X:00 vs +0X00.Lotuseater
@Ja͢ck does this need down-voting, then? A slight difference is usually a bad idea.Hijacker
@Hijacker I don't see a reason to down-vote this answer; technically, both 'c' and DATE_ISO8601 produce valid ISO8601 time representations.Lotuseater
I added a note to answer.Mccray
@Ja͢ck DATE_ISO8601 does not produce a valid ISO8601 representation. DATE_ATOM does thoughRialto
@LeeButler is there a bug report for reference?Lotuseater
@Ja͢ck I'm not sure, but it's documented in the Php docs that it's not quite compatible.Rialto
@LeeButler with that naming of the constant, it seems reason enough to classify it as a bugLotuseater
I agree with @LeeButler, the DATE_ISO8601 does not produce a valid ISO8601 string. This is very confusing, but I doubt PHP would fix that, since it would be a BC break for them.Insuperable
R
8

How to convert from ISO 8601 to unixtimestamp :

strtotime('2012-01-18T11:45:00+01:00');
// Output : 1326883500

How to convert from unixtimestamp to ISO 8601 (timezone server) :

date_format(date_timestamp_set(new DateTime(), 1326883500), 'c');
// Output : 2012-01-18T11:45:00+01:00

How to convert from unixtimestamp to ISO 8601 (GMT) :

date_format(date_create('@'. 1326883500), 'c') . "\n";
// Output : 2012-01-18T10:45:00+00:00

How to convert from unixtimestamp to ISO 8601 (custom timezone) :

date_format(date_timestamp_set(new DateTime(), 1326883500)->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2012-01-18T05:45:00-05:00
Recapture answered 3/4, 2017 at 18:32 Comment(0)
I
6

ISO 8601 is basically represented in PHP as "Y-m-d\TH:i:sP"

You can get this value from a constant:

DateTime::ATOM - for PHP versions below 7.2 (was removed)

DateTimeInterface::ATOM - for PHP versions since 7.2

Intransigent answered 4/8, 2021 at 13:16 Comment(1)
DateTime::ATOM has not been removed in PHP 7.2.Goodsell
C
5

If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21
Cord answered 13/11, 2017 at 17:23 Comment(1)
Similar solution is mentioned in the comments given to the accepted answerBrickle
A
5

$datetime->format('Y-m-d\TH:i:s.u\Z') should give the proper format, with the "T" separator, "Z" timezone (make sure to convert to UTC first) and microseconds (omit .u if you don't intend to support fractional seconds).

See https://mcmap.net/q/161151/-in-an-iso-8601-date-is-the-t-character-mandatory for discussion why should use T

Ambrosane answered 30/3, 2022 at 2:37 Comment(0)
C
4

According to PHP offcial documentation you can simply format it to:

echo $objDateTime->format('c'); // ISO8601 formated datetime
echo $objDateTime->format(DateTime::ISO8601); // Another way to get an ISO8601 formatted string
Clareclarence answered 7/10, 2021 at 14:0 Comment(0)
I
2

You can try this way:

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DATE_ATOM);
Ingar answered 3/9, 2020 at 10:50 Comment(1)
Using DATE_ATOM and c were already posted on this page years earlier.Frostwork
B
1

To represent the date "2010-12-30 23:21:46" to the ISO 8601 format. Here's how you can do it:

<?php
$date = 2010-12-30 23:21:46;
$iso8601_date = date('c', strtotime($date)); // Convert to ISO 8601 format
?>

If you are getting date from your Database try:

<?php
$date = $row['date']; // Assuming $row['date'] contains "2010-12-30 23:21:46"
$iso8601_date = date('c', strtotime($date)); // Convert to ISO 8601 format

Call your Output

<?php echo($iso8601_date) ?>
Balanced answered 18/2 at 13:5 Comment(2)
Hi, welcome to SO. When answering questions please try to provide answers that haven't already been given. You've just submitted a solution that has already been posted.Ruthie
Answer already existsRuthie
P
0

You can also get your timestamps conversion via mutation inside modal like this

class YourModal extends Model
{
    public function getCreatedAtAttribute($date)
    {
        return date(DATE_ISO8601, strtotime($date)); // ISO 8601 Date Format
    }
}
Phyle answered 12/8, 2022 at 7:18 Comment(0)
G
0

Try this out

public static function toISO8601(string $dateString): string { 
    $dateTime = new \DateTime($dateString, new \DateTimeZone('UTC'));
    return $dateTime->format('Y-m-d\\TH:i:s.vp');
}

Output will be: 2010-12-30T04:56:00.000Z

Garnierite answered 9/9, 2023 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.