简体   繁体   English

在MySQL中,如何将此字符串转换为日期?

[英]In MySQL, how to convert this string to a date?

I am creating a mysql db with a php frontend. 我正在创建一个带有php前端的mysql数据库。 The data it will use is extracted from another larger db and contains a date/time field which looks like this - 20120301073136 - which records when an event happened. 它将使用的数据从另一个较大的数据库中提取,并包含一个日期/时间字段,如下所示 - 20120301073136 - 记录事件发生的时间。

I understand that this might be a UNIX timestamp? 我知道这可能是UNIX时间戳吗? Not sure. 不确定。

I want to be show this field in the tables in my PHP webpage as a readable date and time - 我希望在PHP网页的表格中显示此字段作为可读日期和时间 -

ie something like 01-Mar-2012 07:31:36 or similar 即像01-Mar-2012 07:31:36或类似的东西

Should I try and convert it with SQL command or let PHP format it? 我应该尝试使用SQL命令转换它还是让PHP格式化它? And, what is the code to do so? 而且,这样做的代码是什么?

BTW, it is important that I can sort the data (in SQL and in the PHP table) into date order - ie in the order that these events happened. 顺便说一句,重要的是我可以将数据(在SQL和PHP表中)按日期顺序排序 - 即按照这些事件发生的顺序排序。

Thanks in advance for your help - Ive learnt a lot here already 在此先感谢您的帮助 - 我已经在这里学到了很多东西

J Ĵ

You can convert it to a datetime directly in your SQL query. 您可以直接在SQL查询中将其转换为datetime Example: 例:

select cast(20120301073136 as datetime)

You can also order that with no need to convert it since it is a number in the format YYYYMMDDHHmmss 您也可以订购,无需转换,因为它是YYYYMMDDHHmmss格式的数字

select * from yourTable
order by yourDateTimeField

You should make use of the MYSQL DATE functions. 您应该使用MYSQL DATE函数。 Check the docs before asking simple questions. 在提出简单问题之前检查文档。 http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html . http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

Also you can sort the dates directly in your query using ORDER BY. 您还可以使用ORDER BY直接在查询中对日期进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM