MySQL select formatted date from millisecond field

痞子三分冷 提交于 2020-02-17 09:00:12

问题


I have a column in a MySQL database that contains a date as milliseconds (epoch). I want to build an SQL query that formats the date as something human readable (day, month, year, hours, minutes, seconds in any format and time zone). Is there an SQL (or MySQL-specific) function to do this?


回答1:


Try using the FROM_UNIXTIME function like this as given in the manual

SELECT FROM_UNIXTIME(1196440219);
 -> '2007-11-30 10:30:19'

You could also use formatting like this

mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),
    ->                      '%Y %D %M %h:%i:%s %x');
    -> '2007 30th November 10:30:59 2007'



回答2:


If you want to get the microsecond from a field, use %f,

select FROM_UNIXTIME(DATE_COLUMN/1000,'%Y-%M-%d %H:%i:%s %f') from TABLE_NAME;

+-------------------------------------------------------+
| FROM_UNIXTIME(CREATETIME/1000,'%Y-%M-%d %H:%i:%s %f') |
+-------------------------------------------------------+
| 2016-March-18 16:02:54 342000                         |
+-------------------------------------------------------+

Source : MYSQL DATE_FORMAT




回答3:


CREATE DEFINER=`root`@`localhost` FUNCTION `ConvertTimeDelta`(duration int) RETURNS 
varchar(20) CHARSET utf8mb4
    DETERMINISTIC
BEGIN
 DECLARE time_delta VARCHAR(20);
 DECLARE date_format VARCHAR(20);
 SET date_format = IF (duration > 3599999, '%H:%i:%s', '%i:%s');
 SET time_delta = TIME_FORMAT(SEC_TO_TIME(duration/1000), date_format);
 RETURN time_delta;
END

For example select ConvertTimeDelta(4800240) result = 01:20:00 select ConvertTimeDelta(35076) result = 00:35



来源:https://stackoverflow.com/questions/18176088/mysql-select-formatted-date-from-millisecond-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!