欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用postgresql獲取當(dāng)前或某一時(shí)間段的年月日

 更新時(shí)間:2023年07月22日 14:03:38   作者:今晚偷月亮的鄰居  
這篇文章主要給大家介紹了關(guān)于使用postgresql獲取當(dāng)前或某一時(shí)間段的年月日的相關(guān)資料,在PostgreSQL中可以使用函數(shù) NOW() 來查詢當(dāng)前時(shí)間,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下

最近寫代碼遇到關(guān)于獲取某一時(shí)間年月日的需求,特此寫一篇文章便于自己記錄

1.獲取當(dāng)前時(shí)間

select now();                    
--返回:2022-12-07 15:53:15.881711+08
 
select current_date;      
--返回:2022-12-07
 
select current_timestamp;
--返回:2022-12-07 15:56:28.729581+08
 
select current_time;
--返回:15:56:50.155444+08

2.獲取當(dāng)前月份的第一天

select date_trunc('month',current_date)::DATE;
--返回:2022-12-01

3.根據(jù)當(dāng)前日期獲取次日、次月、前年

select (current_date + INTERVAL '1 day')::DATE;
--根據(jù)當(dāng)前日期獲取次日,返回:2022-12-08
select date_trunc('month',(current_date + INTERVAL '1 month'))::DATE;
--根據(jù)當(dāng)前日期獲取次月,返回:2023-01-01
select (current_date - INTERVAL '2 YEAR')::DATE;
--根據(jù)當(dāng)前日期獲取前年,返回:2020-12-07

如果要獲取“周”的周期的時(shí)間 把day、month或year改成week即可,2 year那里加不加s都可以執(zhí)行。

4.根據(jù)第三步的內(nèi)容,我們還可以獲取上一月/年的最后一天

select (date_trunc('month',current_date) - interval'1 day')::DATE;
--首先用date_trunc函數(shù)獲取當(dāng)月的第一天的日期,然后再倒退一天,返回:2022-11-30
select (date_trunc('year',current_date) - interval'1 day')::DATE;
--同上,首先用date_trunc函數(shù)獲取今年的第一天的日期,然后再倒退一天,返回:2021-12-31

這里注意如果我們要獲取上一年前一個(gè)月的第一天日期或最后一天日期,即我現(xiàn)在的時(shí)間是2022-12-07,我想獲取2021年11月第一天的日期或最后一天,寫法應(yīng)該是

select (date_trunc('year',current_date) - interval'2 month')::DATE;
--從當(dāng)前日期2022-12-07獲取2021年11月第一天的日期,返回:2021-11-01
select ((date_trunc('year',current_date) - interval'1 month')-INTERVAL '1 day')::DATE;
--從當(dāng)前日期2022-12-07獲取2021年11月最后一天的日期,返回:2021-11-30
--不知道有沒有更簡(jiǎn)易的方法,希望學(xué)習(xí)下

5.根據(jù)第四步的思路,我們可以獲取當(dāng)月最后一天的日期

select (date_trunc('month',current_date) + interval'1 month - 1 day')::DATE;
--首先用date_trunc函數(shù)獲取當(dāng)月的第一天的日期,接著再加一個(gè)月,最后再減一天,返回:2022-12-31

6.雖然前幾步最后都轉(zhuǎn)成了日期格式,但也可以截取任意日期的時(shí)分秒

SELECT substr(to_char(CURRENT_TIMESTAMP, 'yyyy-mm-dd hh24:mi:ss'),12,8);
--返回:16:19:34

總結(jié)

到此這篇關(guān)于使用postgresql獲取當(dāng)前或某一時(shí)間段的年月日的文章就介紹到這了,更多相關(guān)postgresql獲取年月日內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論