Home >Database >Mysql Tutorial >How to Convert MySQL Date Strings like 'Apr 15 2012 12:00AM' to UNIX Timestamps?

How to Convert MySQL Date Strings like 'Apr 15 2012 12:00AM' to UNIX Timestamps?

DDD
DDDOriginal
2024-12-13 20:31:15583browse

How to Convert MySQL Date Strings like

MySQL: Converting Date Strings to UNIX Timestamps

Converting date strings to UNIX timestamps is a common task in data processing. Here's how to address this need in MySQL.

Problem:

A database returns date strings in the format "Apr 15 2012 12:00AM" including the "AM" suffix. Converting this format using the CONVERT function has not been successful.

Solution:

To convert the given date string to a UNIX timestamp, use the STR_TO_DATE and UNIX_TIMESTAMP functions. The following query demonstrates this:

SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'));

Additional Considerations:

If you also need to change the date format, use the FROM_UNIXTIME function. For example:

SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p');

The above is the detailed content of How to Convert MySQL Date Strings like 'Apr 15 2012 12:00AM' to UNIX Timestamps?. 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