如何从字符串中提取日期

时间:2012-07-24 21:28:16

标签: mysql

我已将日期保存为字符串,例如:Fri Apr 04 15:58:43 BST 2014 这一年总是在最后,我想查询以获得年份少于特定年份的记录,比如2012年。这可能吗?怎么样?是否有可能从mysql修复此问题?即,将日期从字符串转换为日期?

2 个答案:

答案 0 :(得分:4)

您可以使用MySQL STR_TO_DATE()函数将这些值转换为MySQL日期:

mysql> select str_to_date('Fri Apr 04 15:58:43 BST 2014','%a %b %d %H:%i:%S BST %Y');
+------------------------------------------------------------------------+
| str_to_date('Fri Apr 04 15:58:43 BST 2014','%a %b %d %H:%i:%S BST %Y') |
+------------------------------------------------------------------------+
| 2014-04-04 15:58:43                                                    |
+------------------------------------------------------------------------+
1 row in set (0.00 sec)

这是一个粗略的示例,使用您的示例字符串来说明一个查询,以返回2012年之前的日期所有行。它将需要全表扫描,因此它不会很快,但它说明了您需要的基本概念做:

select *
from your_table
where str_to_date(your_column,'%a %b %d %H:%i:%S BST %Y') < '2012-01-01'

答案 1 :(得分:1)

这是一个基线查询

SELECT REVERSE(LEFT(REVERSE('Fri Apr 04 15:58:43 BST 2014'),4));

这里执行

mysql> SELECT REVERSE(LEFT(REVERSE('Fri Apr 04 15:58:43 BST 2014'),4));
+----------------------------------------------------------+
| REVERSE(LEFT(REVERSE('Fri Apr 04 15:58:43 BST 2014'),4)) |
+----------------------------------------------------------+
| 2014                                                     |
+----------------------------------------------------------+
1 row in set (0.00 sec)

mysql>
OMG我在想什么?我实际上正在解码它

SET @datestring = 'Fri Apr 04 15:58:43 BST 2014';
SELECT CONCAT(YYYY,'-',MM,'-',DD,' ',HHMMSS) dt FROM
(SELECT REVERSE(LEFT(REVERSE(@datestring),4)) as YYYY,
SUBSTR(FLOOR((LOCATE(LEFT(SUBSTR(@datestring,5),3),'JanFebMarAprMayJunJulAugSepOctNovDec')+2)/3)+100,2) MM,
SUBSTR(@datestring,9,2) DD,
SUBSTR(@datestring,12,8) HHMMSS) A;

我的解码工作

mysql> SET @datestring = 'Fri Apr 04 15:58:43 BST 2014';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT CONCAT(YYYY,'-',MM,'-',DD,' ',HHMMSS) dt FROM
    -> (SELECT REVERSE(LEFT(REVERSE(@datestring),4)) as YYYY,
    -> SUBSTR(FLOOR((LOCATE(LEFT(SUBSTR(@datestring,5),3),'JanFebMarAprMayJunJulAugSepOctNovDec')+2)/3)+100,2) MM,
    -> SUBSTR(@datestring,9,2) DD,
    -> SUBSTR(@datestring,12,8) HHMMSS) A
    -> ;
+---------------------+
| dt                  |
+---------------------+
| 2014-04-04 15:58:43 |
+---------------------+
1 row in set (0.00 sec)

mysql>