1. 程式人生 > 實用技巧 >Mysql 字串、時間、時間戳相互轉換,相減獲取秒數

Mysql 字串、時間、時間戳相互轉換,相減獲取秒數

涉及的函式
date_format(date, format) 函式
unix_timestamp() 函式
str_to_date(str, format) 函式
from_unixtime(unix_timestamp, format) 函式

1.字串轉化成時間
select
str_to_date('2019-09-12 00:16:50','%Y-%m-%d %H:%i:%s'),
str_to_date('2019-09-12 00:16:50','%Y-%m-%d %H')

2019-09-12 00:16:50    2019-09-12 00:00:00


2.字串轉化成時間戳
select
unix_timestamp('2019-09-12 00:00:50'),

unix_timestamp('2019-09-12 00:01:00');

1568217650    1568217660


3.時間轉換成字串
select
date_format(now(), '%Y-%m-%d'),
date_format(now(), '%Y-%m-%d %H:%i:%s')

2020-08-24    2020-08-24 14:51:26


4.時間轉換成時間戳
select
unix_timestamp(now());

1598251906


5.時間戳轉換成時間
select from_unixtime(1598250986);

2020-08-24 14:36:26


6.時間戳轉成成字串

select from_unixtime(1598250986,'%Y-%m-%d');

2020-08-24


要想獲得正確的時間相減秒數,有以下三張方式:
1、time_to_sec(timediff(t2, t1))
2、timestampdiff(second, t1, t2)
3、unix_timestamp(t2) -unix_timestamp(t1)


列子:
select time_to_sec(timediff(str_to_date('2019-09-12 00:17:50','%Y-%m-%d %H:%i:%s'), str_to_date('2019-09-12 00:16:50','%Y-%m-%d %H:%i:%s')))

60


select timestampdiff(second, str_to_date('2019-09-12 00:17:50','%Y-%m-%d %H:%i:%s'), str_to_date('2019-09-12 00:16:50','%Y-%m-%d %H:%i:%s'))

-60


select unix_timestamp(str_to_date('2019-09-12 00:17:50','%Y-%m-%d %H:%i:%s')) -unix_timestamp(str_to_date('2019-09-12 00:16:50','%Y-%m-%d %H:%i:%s'))

60