mysql日期和时间格式的相互转换

一、时间戳和字符串的转换

1、日期转字符串

函数:date_format(date, format)

举例:

    select date_format(now(),'%Y-%m-%d %H:%i:%S');
    结果:2017-10-29 14:02:54
    

2、日期转时间戳

函数:unix_timestamp(data)

举例:

    select unix_timestamp(now());  
    结果:1509257408
    

 

 

 

3、字符串转日期

函数:str_to_date(str,format);注:format格式必须和str的格式相同,否则返回空

举例:

select str_to_date('2017-10-29 10:01:01', '%Y-%m-%d %H:%i:%S')

 结果:2017-10-29 10:01:01
select str_to_date('2017-10-29 ', '%Y-%m-%d %H:%i:%S')

结果:2017-10-29 00:00:00
 

4、时间戳转日期

函数:from_unixtime(time-stamp);

举例:

   select from_unixtime(1509257408); 
   结果:2017-10-29 14:10:08

5、时间戳转字符串

函数:from_unixtime(time-stamp,format);

举例:

    select from_unixtime(1509257408,'%Y~%m~%d %H:%i:%S'); 
    结果:2017~10~29 14:02:08

 
posted @ 2022-08-02 14:20  一朵盛开的腊梅花  阅读(7684)  评论(0编辑  收藏  举报