Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
–
–
–
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'));
–
–
–
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.
–
–
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
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
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
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
$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://stackoverflow.com/a/9532375/65387 for discussion why should use T
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
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.