Caleb
Caleb

Reputation: 2353

problem converting calendar to java.util.Date

I need to create a java.util.Date object with an Australian timezone. this object is required for tag libraries used in downstream components (so I'm stuck with Date).

Here's what I have attempted:

TimeZone timeZone = TimeZone.getTimeZone("Australia/Sydney");
GregorianCalendar defaultDate = new GregorianCalendar(timeZone);
Date date = defaultDate.getTime();

However, "date" always returns the current local time (in my case, ET). What am I doing wrong here? Is it even possible to set a Date object with a different timezone?

Update:

Thanks for the responses! This works if I want to output the formatted date as a string, but not if I want to return a date object. Ex:

Date d = new Date();
DateFormat df = new SimpleDateFormat();
df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));

String formattedDate = df.format(d);   // returns Sydney date/time
Date myDate = df.parse(formattedDate); // returns local time(ET)

I think I'm going to end up reworking our date taglib.

Upvotes: 2

Views: 10062

Answers (2)

icyrock.com
icyrock.com

Reputation: 28628

getTime is an Unix time in seconds, it doesn't have the timezone, i.e. it's bound to UTC. You need to convert that time to the time zone you want e.b. by using DateFormat.

import java.util.*;
import java.text.*;

public class TzPrb {
    public static void main(String[] args) {
        Date d = new Date();
        System.out.println(d);

        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
        System.out.println(df.format(d));
        df.setTimeZone(TimeZone.getTimeZone("Europe/London"));
        System.out.println(df.format(d));
    }
}

Upvotes: 1

BalusC
BalusC

Reputation: 1109875

Is it even possible to set a Date object with a different timezone?

No, it's not possible. As its javadoc describes, all the java.util.Date contains is just the epoch time which is always the amount of seconds relative to 1 january 1970 UTC/GMT. The Date doesn't contain other information. To format it using a timezone, use SimpleDateFormat#setTimeZone()

Upvotes: 5

Related Questions