PostgreSQL 计算指定的日期时间相对于指定的日期经过了多少秒

本文介绍了一个自定义函数,用于计算指定日期时间相对于指定日期的秒数差异,并提供了判断给定年份是否为闰年的函数。通过具体示例展示了如何使用这些函数。
/****************************************************************************************
    计算指定的日期时间相对于指定的日期经过了多少秒
drop function if exists date_diff_second(timestamptz);
****************************************************************************************/
create or replace function  date_diff_second(timestamptz)
  returns float8
as $$
	with cte as(
		select ($1-($1::date)) as diff
	)select 
		(
			(extract(hour from diff) * 3600) +
			(extract(minute from diff) * 60) +
			extract(second from diff)
		)
	from cte;
$$ language sql strict;
--计算相对于2018-04-12日经过了多少秒
select date_diff_second('2018-04-12 10:11:09.043825+08'::timestamptz)
--验证计算结果
select '2018-04-12 10:11:09.043825+08', ('2018-04-12'::date + make_interval(secs=>36669.043825))::timestamptz




判断闰年还是平年,闰年一年有366天,平年一年有365天
遵循的规律为: 四年一闰,百年不闰,四百年再闰.
摘自postgresql10.3源码src\include\utils\datetime.h(273)

#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
/****************************************************************************************
    判断闰年还是平年,闰年一年有366天,平年一年有365天
drop function if exists isleap(timestamp);
drop function if exists isleap(timestamptz);
drop function if exists isleap(date);
****************************************************************************************/
create or replace function  isleap(timestamptz)
  returns boolean
as $$
	select (((y) % 4) = 0 and (((y) % 100) <> 0 or ((y) % 400) = 0))
		from cast(extract(year from $1) as integer ) as y
$$ language sql strict;

create or replace function  isleap(timestamp)
  returns boolean
as $$
	select (((y) % 4) = 0 and (((y) % 100) <> 0 or ((y) % 400) = 0))
		from cast(extract(year from $1) as integer ) as y
$$ language sql strict;

create or replace function  isleap(date)
  returns boolean
as $$
	select (((y) % 4) = 0 and (((y) % 100) <> 0 or ((y) % 400) = 0))
		from cast(extract(year from $1) as integer ) as y
$$ language sql strict;

验证结果:

with cte as(
    select (case when isleap(year) then 
                366
            else
                365
            end) as days
    from generate_series(1900,2018-1) as year
),calc as(
    select sum(days) as f1,('2018-01-01'::date - '1900-01-01'::date )  as f2 from cte
)select *, f1*24*3600 from calc

  f1   |  f2   |  ?column?  
-------+-------+------------
 43099 | 43099 | 3723753600
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kmblack1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值