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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM