Possible bug
The formatter is using an incorrect identifier for the hours. hh
means " Hour in am/pm (1-12)", so it works with 12h format and a AM/PM marker. Since the formatter does not print the AM/PM marker, this is most likely a bug as it will not differentiate morning from afternoon, and return the same formatted String
for two different dates.
You either want to use HH
instead, which is "Hour in day (0-23)", or print the AM/PM marker with a
.
Thread safety
private final static DateFormat DF =
new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
This is a source of problems, because SimpleDateFormat
is not a thread-safe class:
It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
With using a SimpleDateFormat
as a constant, the same instance will be shared. If you happen to call the method formatTime
from multiple threads at the same time, anything could happen; from an exception thrown, a wrong result, to, even worse, a right result sometimes. This code looks like it lives in a utility class, so all the more reasons it could be used concurrently.
The simple solution here is to let the method formatTime
create the instance of SimpleDateFormat
when it is called, with
public static String formatTime(long time) {
return new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH).format(time);
}
If creating an instance of SimpleDateFormat
each time the method is called turns out to be slow for your purposes, you could use a ThreadLocal
, like shown on Stack Overflow.
A better solution if you're under Java 8 is to use DateTimeFormatter
, which is a thread-safe class.
private final static DateTimeFormatter DF =
DateTimeFormatter.ofPattern(DATE_FORMAT, Locale.ENGLISH);
public static String formatTime(long time) {
Instant instant = Instant.ofEpochMilli(time);
return DF.format(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
}