postgresql日期和时间比较

DB里保存到时分秒,需要和年月日比较。

select date_trunc('day',now())=date_trunc('day',date('20200615'))			--true
select date_trunc('day',date('20200611'))					--2020-06-11 00:00:00+00
select * from users where date_trunc('day',birthday)=date_trunc('day',date('20200401'))

db里存储date或者timestamp字段,需要和字符串比较时,建议先使用to_date或者to_timestamp转换。
测试发现pgsql往类型为timestamp的列插入字符串数据,或者用date/timestamp类型的数据跟字符串数据作比较时,会自动转换成对应的date/timestamp。
oracle未测试。

select to_date('2019-01-15 18:33:41','yyyy-MM-dd hh24:mi:ss');
select to_timestamp('2019-01-15 18:33:41','yyyy-MM-dd hh24:mi:ss');
select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')= to_timestamp('2019-01-15 00:00:00','yyyy-MM-dd hh24:mi:ss');
>>true
select to_timestamp('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')- to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss');
>>"18:33:42"
select to_timestamp('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019/01/15';
>>false

select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019/01/15';
>>true
select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019-01-15';
>>true
select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='20190115';
>>true
select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019/01-15';
>>ERROR:  date型の入力構文が不正です: "2019/01-15"


SELECT 
	time,
	to_timestamp('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss'),
	time=to_timestamp('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss'),
	time,to_date('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss'),
	time=to_date('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss')
FROM public.product where id =21;
>>"2011-12-13 14:15:16+09"
>>"2011-12-13 14:15:16+09"
>>true
>>"2011-12-13 14:15:16+09"
>>"2011-12-13"
>>false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值