简体   繁体   中英

compare time stamp stored in database in java

I am storing current time stamp in database table using now() [example- 20160807000133 ] And i want to compare this time stamp stored in table with current time stamp in java.

How to do that?

My main task is to check whether data stored in table is within certain time interval with respect to current time.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat . The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP .

String input = "20160807000133";
DateTimeFormatter BASIC_ISO_DATETIME = DateTimeFormatter.ofPattern ( "uuuuMMddHHmmss" );  //  Make constant somewhere in your codebase.

LocalDateTime ldt = LocalDateTime.parse ( input , BASIC_ISO_DATETIME );

Dump to console.

System.out.println ( "input: " + input + " | ldt: " + ldt );

input: 20160807000133 | ldt: 2016-08-07T00:01:33

Time Zone

Note that your input data makes the mistake of failing to include any information about time zone or offset-from-UTC. As such, it does not represent a moment on the timeline. If that data were intended for Paris that would be a different moment than if it were meant for Montréal.

If you know the context intended a certain time zone, apply a ZoneId before using this value in your database query.

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone ( zoneId );

zdt: 2016-08-07T00:01:33-04:00[America/Montreal]

Database

If your JDBC driver complies with JDBC 4.2 or later, you should be able to directly pass/fetch the java.time types via setObject & getObject .

If not, fallback to converting using the new methods added to the old classes. For java.sql.Timestamp that means going through an Instant , a moment on the timeline in UTC with a resolution of up to nanoseconds. We can extract an Instant object from our ZonedDateTime .

java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );
myPreparedStatement.setTimestamp( ts );

…and…

java.sql.Timestamp ts = myResultSet.getTimestamp( 1 );
Instant instant = ts.toInstant();
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = instant.atZone ( zoneId );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM