sqlpostgresqltimestampto-timestamp

Compare a character varying with a timestamp


I'm trying to compare a character varying with a timestamp in postgresSQL.

I want to get all the values that are before current time compared to the character varying timestamp.

Would this compare correctly?

WHERE to_timestamp('2018-12-25T06:00:00+01:00', 'YYYY-MM-DD HH24:MI:SS') < now()

Solution

  • Not exactly. There are timezone values in the literals which should be parsed. Compare:

    select
        to_timestamp('2018-12-25T06:00:00+01:00', 'YYYY-MM-DD HH24:MI:SS') as "seems ok",
        to_timestamp('2018-12-25T07:00:00+02:00', 'YYYY-MM-DD HH24:MI:SS') as "but this is wrong!",
        to_timestamp('2018-12-25T06:00:00+01:00', 'YYYY-MM-DD HH24:MI:SS+TZH:TZM') as "ok",
        to_timestamp('2018-12-25T07:00:00+02:00', 'YYYY-MM-DD HH24:MI:SS+TZH:TZM') as "ok too"
    
            seems ok        |   but this is wrong!   |           ok           |         ok too         
    ------------------------+------------------------+------------------------+------------------------
     2018-12-25 06:00:00+01 | 2018-12-25 07:00:00+01 | 2018-12-25 06:00:00+01 | 2018-12-25 06:00:00+01
    (1 row)