Reputation: 274
This question is rather complicated and I don't know if it's been asked before because I don't know how to phrase the problem in the search box.
Here's the code:
public class SomeClass
{
private static final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public static String toUTCDateString(Date date)
{
df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
return df.format(date);
}
/* more static methods */
}
The static member df
will be re-used again in more static methods, but I need to have its time zone set to "UTC" first. Is there a way to call .setTimeZone("UTC")
just once and for all? Or do I have to call .setTimeZone("UTC")
in each static method?
Upvotes: 2
Views: 314
Reputation: 109557
Unfortunately! SimpleDateFormat is not trread-safe: it keeps an internal state, and used at the same time havoc arises.
This "solves" your problem as you have to change the API.
public static DateFormat df()
{
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
return df;
}
In Java 8 using other, nicer classes this issue is solved.
By the way yyyy-MM-dd is the ISO standard.
Upvotes: 3
Reputation: 46841
Use Static Initialization Blocks
A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
Sample code:
public class SomeClass
{
private static final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//Static Initialization Blocks
static{
df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
}
public static String toUTCDateString(Date date)
{
return df.format(date);
}
/* more static methods */
}
Upvotes: 7