時間戳轉成日期
select distinct from_unixtime(1441565203,‘yyyy/MM/dd HH:mm:ss’) from test_date;
日期轉成時間戳
select distinct unix_timestamp(‘20111207 13:01:03’) from test_date; // 默認格式爲“yyyy-MM-dd HH:mm:ss“
select distinct unix_timestamp(‘20111207 13:01:03’,‘yyyyMMdd HH:mm:ss’) from test_date;
yyyymmdd和yyyy-mm-dd日期之間的切換
方法1: from_unixtime+ unix_timestamp
–20181205轉成2018-12-05
select from_unixtime(unix_timestamp(‘20181205’,‘yyyymmdd’),‘yyyy-mm-dd’) from dual;
–2018-12-05轉成20181205
select from_unixtime(unix_timestamp(‘2018-12-05’,‘yyyy-mm-dd’),‘yyyymmdd’) from dual;
方法2: substr + concat
–20181205轉成2018-12-05
select concat(substr(‘20181205’,1,4),’-’,substr(‘20181205’,5,2),’-’,substr(‘20181205’,7,2)) from dual;
–2018-12-05轉成20181205
select concat(substr(‘2018-12-05’,1,4),substr(‘2018-12-05’,6,2),substr(‘2018-12-05’,9,2)) from dual;
注:
1.值得注意的是,時間戳有可能是毫秒級的,然後這時候直接使用from_unixtime(1441565203,‘yyyy/MM/dd HH:mm:ss’)的話就會得到很奇怪的日期了,這時候要這樣from_unixtime(cast(151331629920/1000 as int)),同樣的,時間轉成毫秒級的時間戳也要乘以1000,如:unix_timestamp(‘2018-12-18 00:38:50’)*1000
2.如何區分時間戳是秒級還是毫秒級呢?一般來說,常見的時間戳是10位數的,13位數的時間戳就是毫秒級的