user2686860
user2686860

Reputation: 107

Java compare time with timezone

My table has a column whose datatype is timestamp with timezone. The value in database is something like

I have a tomcat server which is running in the UTC timezone. I know how to compare two dates which have the same timezone, but I am unable to figure out if I can compare server time with db time which have timezone details like -7.00, -8.00 or +5:30.

Is there a way in java to convert a time from database to common timezone and then compare it to another time?

Upvotes: 1

Views: 4439

Answers (1)

StoopidDonut
StoopidDonut

Reputation: 8617

You can use joda-time to conveniently parse your offsets and dates to a common on (say UTC).

Taking the example of the 2 time instances mentioned in your post:

String time1 = "26-NOV-01 12.00.00.000000000 PM -07:00";
String time2 = "26-NOV-01 12.00.00.000000000 PM -08:00";
DateTimeFormatter parser = DateTimeFormat.forPattern("dd-MMM-yy hh.mm.ss.SSSSSSSSS aa Z").withZoneUTC(); // joda time date time formatter instance with a common UTC timezone

System.out.println(parser.parseDateTime(time1)); // parse to date time - gives: 2001-11-26T19:00:00.000Z
System.out.println(parser.parseDateTime(time2)); // parse to date time - gives: 2001-11-26T20:00:00.000Z

System.out.println(parser.parseDateTime(time2).compareTo(parser.parseDateTime(time1))); // Comparing both the times here - gives: 1

Here, you are able to compare the 2 times with different offsets and normalize them to a common timezone. Similarly, you can choose the timezone of your choice and work these time instances conveniently.

Upvotes: 2

Related Questions