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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 10:26:30350browse

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

Converting ISO8601 to MySQL DATE Format in PHP

When working with dates, it is often necessary to convert between different formats. ISO8601 and MySQL DATE are two common formats used in web development. This guide demonstrates how to convert a date in ISO8601 format (e.g., 2014-03-13T09:05:50.240Z) to MySQL DATE format (e.g., 2014-03-13) using PHP.

To convert an ISO8601 date to MySQL DATE format, follow these steps:

  1. Use the strtotime() function: This function takes a date string in ISO8601 format as input and returns a UNIX timestamp.
  2. Format the UNIX timestamp using the date() function: Use the date() function to format the UNIX timestamp as a MySQL DATE string in the format 'Y-m-d'.

Here's an example code snippet that demonstrates the conversion:

<code class="php">$date = '2014-03-13T09:05:50.240Z';

$fixed = date('Y-m-d', strtotime($date));</code>

In this example, $fixed will be assigned the value '2014-03-13', which is the MySQL DATE representation of the ISO8601 date $date.

Note: If strtotime returns 0, it means the date is invalid. You can use a workaround by parsing the ISO8601 string and extracting the date part:

<code class="php">$date = '2014-03-13T09:05:50.240Z';

$fixed = date('Y-m-d', strtotime(substr($date, 0, 10)));</code>

The above is the detailed content of How to Convert ISO8601 Date 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