Convert ISO8601 Timestamp to MySQL DATE Format in PHP
A common task in web development is converting timestamps from ISO8601 format to the MySQL DATE format. Here's a step-by-step guide on how to achieve this in PHP:
1. Use the date Function:
<code class="php">$iso_date = '2014-03-13T09:05:50.240Z'; $mysql_date = date('Y-m-d', strtotime($iso_date));</code>
Explanation:
2. Use the Substring Method to Ignore the Time Portion:
If strtotime returns 0 due to an invalid ISO8601 format, you can modify the logic to ignore the time portion:
<code class="php">$fixed_iso_date = substr($iso_date, 0, 10); // Trim to '2014-03-13' $mysql_date = date('Y-m-d', strtotime($fixed_iso_date));</code>
3. Example Usage:
<code class="php">$iso_date = '2014-03-13T09:05:50.240Z'; $mysql_date = convert_iso8601_to_date($iso_date);</code>
4. Function Definition (Optional):
You can create a reusable function to encapsulate the conversion logic:
<code class="php">function convert_iso8601_to_date($iso_date) { $fixed_iso_date = substr($iso_date, 0, 10); return date('Y-m-d', strtotime($fixed_iso_date)); }</code>
The above is the detailed content of How to Convert ISO8601 Timestamp to MySQL DATE Format in PHP?. For more information, please follow other related articles on the PHP Chinese website!