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

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 08:09:02187browse

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

Converting ISO8601 Timestamps to MySQL DATE Format in PHP

In this article, we'll explore how to efficiently convert timestamps in ISO8601 format to the MySQL DATE format using PHP.

Problem Statement

Given an ISO8601 timestamp, such as "2014-03-13T09:05:50.240Z," our goal is to transform it into the MySQL DATE format, which represents only the date component (e.g., "2014-03-13").

Solution

To achieve this conversion, we will utilize PHP's built-in functions:

<code class="php">$date = '2014-03-13T09:05:50.240Z';
$fixed = date('Y-m-d', strtotime($date));</code>
  1. strtotime: This function converts a string representing a date and time into a Unix timestamp (seconds since January 1, 1970).
  2. date: This function formats a Unix timestamp into a human-readable string or timestamp. By specifying the format 'Y-m-d', we extract only the date component.

Additional Note

Some timestamps in ISO8601 format may not be recognized by the strtotime function. In such cases, you can manually extract the date component using substr:

<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 Timestamps 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