Convert ISO 8601 to unixtimestamp
Asked Answered
C

2

44

How can I convert 2012-01-18T11:45:00+01:00 (ISO 8601) to 1326883500 (unixtimestamp) in PHP?

Cohn answered 18/1, 2012 at 10:48 Comment(0)
B
69

This code converts an ISO 8601 datetime to a Unix timestamp in UTC.

echo date("U",strtotime('2012-01-18T11:45:00+01:00'));

longer version:

$dateTime = new DateTime('2012-01-18T11:45:00+01:00');
$dateTime->setTimezone(new DateTimeZone('UTC'));
$utcTimestamp = $dateTime->getTimestamp();
echo $utcTimestamp;
Belligerence answered 18/1, 2012 at 10:50 Comment(1)
@Cohn in this case no. i thought you may want to use another format of input/outputBelligerence
I
22

To convert from ISO 8601 to unixtimestamp :

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

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

To convert from unixtimestamp to ISO 8601 (GMT) :

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

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
Ichnology answered 20/2, 2016 at 12:45 Comment(1)
Very useful! Thanks much!Roberson

© 2022 - 2024 — McMap. All rights reserved.