简体   繁体   中英

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.

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()

getTime is an Unix time in seconds, it doesn't have the timezone, ie it's bound to UTC. You need to convert that time to the time zone you want eb 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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM