Reputation: 6868
We are developing an API in PHP, MySQL that one of its fields returns a datetime in the format of YYYY-MM-DD HH:MM:SS
. This API in the very near future can be used in different continents. In which ISO
format should I save my datetime
that time offset can be preserved too?
Does this time do the job? Or should I use something like ISO 8601
?
I've also read that in PHP we can return date/time with:
gmdate('Y-m-dTH:i:sZ');
What do you suggest? In what format should I return date/time?
Upvotes: 0
Views: 86
Reputation: 14081
When you deal with dates that can come from various time zones, what you should do is store it as a timestamp in MySQL. In that case, it becomes irrelevant where the information comes from (which continent). This is true for saving data. Now, when it comes to displaying date information to people on different continents, you would have to know their time zone. Using PHP's DateTime
, you can use the timestamp from the database, pair it with DateTimeZone
and show the correct time for that time zone.
Also, when you need to exchange data between various services - providing the timestamp allows the target application to apply any range of time zones for its own formatting purposes. However, all date storage should be without time zone reliance. That's why timestamp plays a huge utility role here - it's always UTC.
Now, let's provide some code so this doesn't become just all-talk.
MySQL's timestamp
data-type stores the value as integer internally, but displays it as datetime.
$mysql_datetime = '2014-10-15 12:58:55'; // this is what you got from the database
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $mysql_datetime); // Now you have the object which can manipulate dates
// Let's assume you have someone in New York who wants to see the date but formatted according to their time zone
$dt->setTimeZone(new DateTimeZone('America/New_York'));
echo $dt->format('Y.m.d, H:i:s'); // Format accepted is the same as for `date()` function.
Upvotes: 1