10 Ocak 2016 Pazar

Java Calendar&Date Comparison

Hello,

Last week, I struggled with date comparisons in Java.
Normally, as you know, java.util.Date and Calendar have necessary functions for comparing operations. But when we talk about Timezone, the issue gets complicated.

You may know, java.util.Date objects do not carry any Timezone information, so when you compare dates with different timezones, you should be careful. You may say that, you would prefer java.util.Calendar instance for this operation. Bingo! That's true, but not complete.

I explore something. You have two calendar instances and you set their timezones correctly. Everything is looking good. When you compare each other with Calendar's functions, i.e. "after", you may be shocked, it gives wrong result. Because, when you create a Calendar, it is created with default system timezone. And when you change its timezone, this does not change its milliseconds property.. Compare methods use milliseconds, so you get wrong answer. You should add the offset milliseconds to calendar's after setting timezone, what am I taking about is this,

(taken from this URL,
http://stackoverflow.com/questions/230126/how-to-handle-calendar-timezones-using-java)

// My default timezone is GMT+2
Date date = new Date();
// get offset for GMT+2
int offset = TimeZone.getDefault().getOffset(date.getTime());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+5"));
System.out.println(cal.getTime());
// get new offset for GMT+5
int newOffset = cal.getTimeZone().getOffset(date.getTime() - offset);
cal.add(Calendar.MILLISECOND, newOffset-offset);
System.out.println(cal.getTime());

Here, as you see, new Calendar object is created with GMT+5 timezone and its milliseconds are set properly. By this, you can use compare methods correctly.

Have a nice day !