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

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐