Tuesday, February 2, 2010

A Date with java.util.Date

Recently I encountered with interesting problem where I wanted to change java.util.Date from one time zone to other. It shouldn't be surprising that its not possible! why ? carry on reading.

When we instantiate Date it's instantiated as System.currentTimeMillis() from the OS. That represents time in mills from a reference date. But then things gets confusing when we try to print this. Lets do one experiment, run same code with different zone selected from your computer.

Date d = new Date();
System.out.println("date "+d);

This will print different sting for same date. This is because toString() implementation of Date takes default time zone of computer to print time zone. If it doesn't find any then it will get GMT time for the date instance.

What to do if we want to display date in time zone other than JVM/OS. We know that Date cannot be used to do that.
What the code below doing?

Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
c.setZome(TimeZone.getTimeZone("IST"));
d = c.getTime();

I guess you answered nothing. That's correct, the whole point is Date doesn't store time zone information. But question about displaying Date in zone other than JVM remains unanswered. Let's answer it.

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setZome(TimeZone.getTimeZone("IST"));
String IST_Date = df.format(d);
System.out.println("DATE if IST zone "+IST_Date);

Now what if I want to create Date instance from IST_Date string.

Date d = df.parse(IST_Date);

1 comment:

  1. Thank You It Helps.

    It have converted the IST format date into GMT format but when I parse the date using Date d = df.parse(IST_Date) then converted date again goes to the IST date format How to do this.

    ReplyDelete