postgresql数据库的 to_date 和 to_timestamp 将 字符串转换为时间格式

数据库中:字符串 转换为 时间格式

二者区别:

        to_data 转换为 普通的时间格式
        to_timestamp 转换可为 时间戳格式
出错场景: 比较同一天 日期大小的时候,很容易出错

例如:
        select current_timestamp from pub_employee
        结果如下:
        
    select current_timestamp <= to_date('2018-03-12 18:47:35','yyyy-MM-dd hh24:mi:ss') flag from pub_employee
    语句中的2018-03-12 18:47:35 要比 current_timestamp当前的时间 大两个小时,
    但是结果如下:

结果是 false
原因是:select to_date('2018-03-12 18:47:35','yyyy-MM-dd hh24:mi:ss') from pub_employee
的结果如下:并不是时间戳


正确的写法
select current_timestamp <= to_timestamp('2018-03-12 18:47:35','yyyy-MM-dd hh24:mi:ss') flag from pub_employee
结果:
为true
因为:select to_timestamp('2018-03-12 18:47:35','yyyy-MM-dd hh24:mi:ss') from pub_employee

    
============================================================
to_date:

方式一:正确
select to_date('2018-03-08','yyyy-MM-dd') from pub_employee
方式二:
select to_date('2018-03-08 18:55:33','yyyy-MM-dd') from pub_employee
方式三:
select to_date('2018-03-08 18:55:33','yyyy-MM-dd hh24:mi:ss') from pub_employee

使用to_date 返回的都是以下结果:

 


to_timestamp:

方式一:
select to_timestamp('2018-03-08','yyyy-MM-dd') from pub_employee
方式二:
select to_timestamp('2018-03-08 18:55:33','yyyy-MM-dd') from pub_employee
方式一和二都是以下格式,虽然都是时间戳,但是后面一截是0

方式三:正确
select to_timestamp('2018-03-08 18:55:33','yyyy-MM-dd hh24:mi:ss') from pub_employee

 

---------------------
作者:大bug
来源:CSDN
原文:https://blog.csdn.net/sky_limitless/article/details/79527665
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @   疯子110  阅读(64073)  评论(3编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2017-06-20 eclipse-在编译项目时js特别慢的问题
2017-06-20 Eclipse中jsp、js文件编辑时,卡死现象解决汇总
点击右上角即可分享
微信分享提示