caibirdcnb caibirdcnb - 4 months ago 14
Java Question

How to use .setTimeZone for a class member?

Experts,
I would like to get current datetime in a given timezone for global usage.

So,
I create a class like below, but it shows syntax error for the df.setTimeZone statement. What is the neat way to achieve this? More specific, I would like to set timezone property for a class member rather than a local variable.

I defined many date format through SimpleDateFormat, how to specify a timezone for all of them? (.setTimeZone seems only for one date format) Thanks.

public class Global {

static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");

df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE"));

static String strDate = df.format(new Date());

}

Answer

If you absolutely must do it with static fields, you need the code to be in a static initializer block:

class Global {

    static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    static {
        df.setTimeZone(TimeZone.getTimeZone("GIVEN_TIMEZONE"));
    }
    static String strDate = df.format(new Date());

}

UPDATE

If you have lot of dates to do like that, with different date formats and/or time zones, it may be better to use a helper method.

class Global {

    static String strDate = format(new Date(), "dd/MM/yyyy", "GIVEN_TIMEZONE");

    private static String format(Date date, String format, String timeZoneID) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        df.setTimeZone(TimeZone.getTimeZone(timeZoneID));
        return df.format(date);
    }

}