常用日期格式轉換


-- 時間戳轉日期
-- yyyyMMdd格式:
select from_unixtime(clktime/1000,'yyyyMMdd') as date_    --20210101
from table
where clktime=1609470888000  --毫秒

-- yyyy-MM-dd格式:
select from_unixtime(clktime/1000,'yyyy-MM-dd') as date_    --2021-01-01
from table
where clktime=1609470888000  --毫秒

-- yyyy-MM-dd HH:mm:ss格式:
select from_unixtime(clktime/1000,'yyyy-MM-dd HH:mm:ss') as date_    --2021-01-01 11:14:48
from table
where clktime=1609470888000  --毫秒


-- 日期轉時間戳
select unix_timestamp('2021-01-01','yyyy-MM-dd') as date_    -- 1609430400   
from tablle

select unix_timestamp('20210101','yyyyMMdd') as date_    -- 1609430400
from table

select unix_timestamp('2021-01-01 11:14:48','yyyy-MM-dd HH:mm:ss') as date_    -- 1609470888
from table


-- 日期轉轉時間戳單位為秒:unix_timestamp('2021-01-01','yyyy-MM-dd')
-- 日期轉轉時間戳單位為毫秒:unix_timestamp('2021-01-01','yyyy-MM-dd')/1000
-- 日期轉時間戳unix_timestamp('日期','格式')中的日期與格式必須一致,否則轉化結果為null


-- 獲取當前日期
select from_unixtime(unix_timestamp(),'yyyy-MM-dd HH:mm:ss') as date_    -- 2021-02-02 16:01:54
from table

select current_timestamp    -- 2021-02-02 16:01:54
from table

select from_unixtime(unix_timestamp(),'yyyy-MM-dd') as date_    -- 2021-02-02
from table

-- 返回具體的日期(年-月-日)    
select to_date('2021-02-02 16:01:54') as date_    -- 2021-02-02
from table

-- 返回年
select year('2021-02-02 10:03:01') as date_    -- 2021
from table

-- 返回月
select month('2021/02/02 10:03:01') as date_    -- 2
from table

-- 返回日
select day('2021-02-02 10:03:01') as date_    -- 2
from table

-- 返回時
select hour('2021-02-02 10:03:01') as date_    -- 10
from table

-- 返回分
select minute('2021-02-02 10:03:01') as date_    -- 3
from table

-- 返回秒
select second('2021-02-02 10:03:01') as date_    -- 1
from table

-- 返回日期在當年的周數
select weekofyear('2021-02-02 10:03:01') as date_    -- 5
from table

-- 返回結束日期減去開始日期的天數
select datediff('2021-02-02','2021-01-02') as date_    -- 31
from table

-- 返回起始日期增加n天后的日期
select date_add('2021-02-02',10) as date_    -- 2021-02-12
from table

-- 返回起始日期減去n天后的日期
select date_sub('2021-02-02',10) as date_    -- 2021-01-23
from table

-- 返回當前月份的第一天
select trunc('2021-02-02','MM') as date_    -- 2021-02-01
from table

-- 返回當前月份的最后一天
select last_day('2021-02-02 10:03:01') as date_    -- 2021-02-28
from table

-- 返回當年的第一天
select trunc('2021-02-02','YEAR') as date_    -- 2021-01-01
from table


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM