Home  >  Article  >  Database  >  How to Convert ISO8601 Timestamp to MySQL DATE Format in PHP?

How to Convert ISO8601 Timestamp to MySQL DATE Format in PHP?

DDD
DDDOriginal
2024-10-25 07:42:291001browse

How to Convert ISO8601 Timestamp to MySQL DATE Format in PHP?

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:

  • date('Y-m-d', ...) formats the timestamp according to the specified pattern (Y-m-d for the DATE format).
  • strtotime($iso_date) converts the ISO8601 timestamp to a Unix timestamp (number of seconds since the Unix epoch).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn