Friday, June 27, 2008

Working with time

It can seem trivial but sometimes working with time can become a real headache.
Here I present a short code snippet showing one common but confusing situation:
if you create two different Calendar objects and print it getting its Date and using 'println()' method they can seem the same.

Please read code comments which clarifies every situation.


import java.util.Calendar;
import java.util.TimeZone;

public class utc {

/**
* @param args
*/
public static void main(String[] args) {
Calendar c1 = Calendar.getInstance(TimeZone
.getTimeZone("Europe/Madrid"));

Calendar c2 = (Calendar) c1.clone();
c2.setTimeZone(TimeZone.getTimeZone("UTC"));

// Print Calendars. By default the toString() Calendar method is called
// and gets a String version of the objects.
// As you can see the String version shows the time zone of the Calendar.
System.out.println("Cal1: " + c1);
System.out.println("Cal2: " + c2);

// Print the Date objects of each Calendar.
// Here the toString method of the Date objects are invoked and this method
// by default translates the Date to the default system timezone. Thus both Dates
// seems equal.
System.out.println("Cal1: " + c1.getTime());
System.out.println("Cal2: " + c2.getTime());

// Finally we get the value of HOUR, MINUTE and SECOND of each calendar and
// prints it on the screen.
int h1 = c1.get(Calendar.HOUR_OF_DAY);
int m1 = c1.get(Calendar.MINUTE);
int s1 = c1.get(Calendar.SECOND);

int h2 = c2.get(Calendar.HOUR_OF_DAY);
int m2 = c2.get(Calendar.MINUTE);
int s2 = c2.get(Calendar.SECOND);

System.out.println("Cal1: " + h1 + ":" + m1 + ":" + s1);
System.out.println("Cal2: " + h2 + ":" + m2 + ":" + s2);
}
}

No comments: