Search code examples
javaoracle11g

comparing the java current timestamp againt column in oracle db


I have column in oracle DB which is stored values in this format

'20-DEC-2022 02.04.19.2424 PM'
'02-DEC-2022 03.14.19.1524 AM'
'02-NOV-2022 11.14.19.1524 PM'
'02-MAY-2022 08.14.19.1524 AM'

From Java, I need to compare with system time against emp_updt_timestmp column. Does below query fetch correct results?

I will pass the current time from java['20-12-2022 04.02.12 PM']. Do I need to pass in this format only from Java?

.select * from emp where emp_updt_timestmp >= to_timestamp('20-12-2022 04.02.12 PM','dd-mm-yyyy hh.mi.ss AM')

Solution

  • You can use a TIMESTAMP literal:

    select *
    from   emp
    where  emp_updt_timestmp >= TIMESTAMP '2022-12-20 16:02:12'
    

    or strings in whatever format you want (so long as the format model matches the format of the string):

    select *
    from   emp
    where  emp_updt_timestmp >= to_timestamp('20-12-2022 04.02.12 PM','dd-mm-yyyy hh.mi.ss AM')
    

    or, for example, an ISO8601 format:

    select *
    from   emp
    where  emp_updt_timestmp >= to_timestamp('2022-12-20T16:02:12','YYYY-MM-DD"T"HH24:MI:SS')
    

    or, better, you can use a prepared statement and bind variables:

    select *
    from   emp
    where  emp_updt_timestmp >= ?
    

    and then in your Java code you can use PreparedStatement.setTimestamp(java.sql.Timestamp) or oracle.jdbc.OraclePreparedStatement.setTIMESTAMP(oracle.sql.TIMESTAMP) to bind the value to it.