PostgreSql 日期类型处理

1. 查询天数据

  1. 查询当天数据
select * from table1 as n
where n.created_time>=current_date;
  1. 查询昨天数据
select * from table1 as n
where n.created_time>=current_date-1 and n.created_time <current_date ;

2. 查询月数据

  1. 查询当月数据
select *
from table1 as n
WHERE extract(YEAR FROM created_time) = extract(YEAR FROM now())
and extract(MONTH FROM created_time) = extract(MONTH FROM now()) 
  1. 查询上月数据
select *
from table1 as n
where created_time >= date_trunc('month',current_date - interval '1' month)
and created_time < date_trunc('month',current_date)

3. 查询年数据

  1. 查询当年数据
select *
from table1 as n
WHERE extract(YEAR FROM created_time) = extract(YEAR FROM now()) ORDER BY created_time
  1. 查询去年数据
select *
from table1 as n
where created_time >= date_trunc('year',current_date - interval '1' year)
and created_time < date_trunc('year',current_date)

4.类型转换

  1. 查询某天:datetime类型的,需要转换为 date 类型,如果你要查询的字段已经是 date 类型则不需要进行转换
    select t_create
    from table
    where t_create::date = to_date(‘2023-02-08’, ‘YYYY-MM-DD’);
  2. string转timestamp类型,按范围查询
    select * from table where create_date >= ‘2023-01-08’::timestamp and create_date < ‘2023-02-08’::timestamp;
  3. 时间戳Long转Timestamp
    select TO_TIMESTAMP(1512490630)
  4. string转data,只能得到年月日,得不到时分秒
    select to_date(‘2023-01-28 12:55:05’)
  5. 当前日期 select current_date
  6. 带时区的时分秒值 select current_time;也可以使用current_time(precision),将结果在四分之一秒的范围内四舍五入到位数,比如select current_time(2);对应没有时区的值:select localtime;
  7. 带时区的年月日时分秒值 select current_timestamp; 对应没有时区的值:select localtimestamp;
  • 17
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 21
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值