Search code examples
javadatedatetimestaticfinal

java final object DateFormat set timezone


I have a database elsewhere that I have to get my data from that is in another timezone.

To get the latest updated elements I need to convert the Date to the timezone of the database so I can only get the lines changed after a specific time.

For communication with the database I created a Java class with all kind of static final elements. I would like to add a static final DateFormat with a SimpleDateFormat and a TimeZone so I can always use this FINAL DateFormat to change the date to the datetime of the database everywhere in the application.

So I have a class:

public class Data_DB {

    static final DateFormat FORMATTER= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}

I can use the DateFormat everywhere in my application, quite nice. But I want to change the TimeZone of formatter too.

public class Data_DB {

    static final DateFormat FORMATTERSD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static final DateFormat FORMATTERDB = FORMATTERSD.setTimeZone(TimeZone.getTimeZone("XXXX/xxxx"));
}

But the return value of FORMATTERSD.setTimeZone(TimeZone.getTimeZone("XXXX/xxxx")) is void.

I do not want to instantiate Data_DB to add the TimeZone to it.

In what way can I solve this to get a static final element FORMATTERDB that I can use everywhere in the application?


Solution

  • You can do like this :

    static final DateFormat FORMATTERSD;
        static {
            FORMATTERSD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            FORMATTERSD.setTimeZone(TimeZone.getTimeZone("XXXX/xxxx"));
        }
    

    The static will be called once.

    Please note that a SimpleDateFormat is not thread safe, if you have multiple thread, it could not work