Home >Backend Development >PHP Tutorial >How to Convert Date Strings to MySQL DATETIME Fields?
Converting Date Strings to MySQL DATETIME Fields
When working with data, it is often necessary to convert date strings to a structured format compatible with database fields. MySQL's DATETIME data type is commonly used to store timestamps and dates with precision. This article provides a solution for converting date strings to a MySQL DATETIME field.
Problem:
You have a list of records with dates stored as strings in the format '04/17/2009' and want to convert them to MySQL DATETIME fields. You intend to iterate through the records using a loop, extracting the old date values and inserting the newly formatted values into a separate field.
Solution:
PHP offers a straightforward way to perform this conversion. Here's a step-by-step approach:
Convert to Timestamp:
To start, convert the date string into a PHP timestamp using the strtotime() function. The timestamp represents the number of seconds since January 1, 1970, 00:00:00 GMT.
<code class="php">$timestamp = strtotime($string);</code>
Format to MySQL DATETIME:
Once you have the timestamp, you can convert it to a MySQL DATETIME format using the date() function. Specify the desired format as "Y-m-d H:i:s."
<code class="php">$datetime = date("Y-m-d H:i:s", $timestamp);</code>
Now you have a formatted datetime string compatible with the DATETIME field in MySQL. You can insert it into the database accordingly.
The above is the detailed content of How to Convert Date Strings to MySQL DATETIME Fields?. For more information, please follow other related articles on the PHP Chinese website!