How to compare dates in datetime fields in Postgresql?

后端 未结 4 785
太阳男子
太阳男子 2020-12-07 10:05

I have been facing a strange scenario when comparing dates in postgresql(version 9.2.4 in windows).
I have a column in my table say update_date with type \'timestamp w

相关标签:
4条回答
  • 2020-12-07 10:12

    When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

    So for update_date = '2013-05-03 14:45:00' your expression will be that:

    '2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'
    

    This is always false

    To solve this problem cast update_date to date:

    select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result
    
    0 讨论(0)
  • 2020-12-07 10:12

    Use Date convert to compare with date: Try This:

    select * from table 
    where TO_DATE(to_char(timespanColumn,'YYYY-MM-DD'),'YYYY-MM-DD') = to_timestamp('2018-03-26', 'YYYY-MM-DD')
    
    0 讨论(0)
  • 2020-12-07 10:29

    @Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:

    SELECT *
    FROM table
    WHERE update_date >= '2013-05-03'::date
    AND update_date < ('2013-05-03'::date + '1 day'::interval);
    
    0 讨论(0)
  • 2020-12-07 10:36

    Use the range type. If the user enter a date:

    select *
    from table
    where
        update_date
        <@
        tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');
    

    If the user enters timestamps then you don't need the ::date + 1 part

    http://www.postgresql.org/docs/9.2/static/rangetypes.html

    http://www.postgresql.org/docs/9.2/static/functions-range.html

    0 讨论(0)
提交回复
热议问题