MySQL 将日期字符串转换为 Unix 时间戳

2021-11-20 00:00:00 datetime timestamp mysql unix-timestamp

如何将以下格式转换为unix时间戳?

How do I convert the following format to unix timestamp?

Apr 15 2012 12:00AM

我从 DB 得到的格式似乎在末尾有 AM.我试过使用以下方法,但没有用:

The format I get from DB seems to have AM at the end. I've tried using the following but it did not work:

CONVERT(DATETIME, Sales.SalesDate, 103) AS DTSALESDATE,  
CONVERT(TIMESTAMP, Sales.SalesDate, 103) AS TSSALESDATE

where Sales.SalesDate value is Apr 15 2012 12:00AM

推荐答案

以下是如何将 DATETIME 转换为 UNIX 时间戳的示例:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

Here's an example of how to convert DATETIME to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

以下是如何更改日期格式的示例:
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')

文档: UNIX_TIMESTAMP, FROM_UNIXTIME

相关文章