Juan.carlos Juan.carlos - 1 month ago 10
Java Question

SimpleDateFormat.format() gives invalid Date

This method generated an invalid date:

final static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
staticString getDate(double seconds) {
Date date = new Date((long)(seconds * 1000));
return dateFormat.format(date);
}


Somehow
1465235513.09794
came as
"2015-06-31T02:33:31.921+0000"
- interesting part is June 31st.

Any clue?

Answer

A wild guess, are you using this in multi-thread program. If that's the case, SimpleDateFormat is not threadsafe. I would rather move the dateFormat into getDate() method. From the Javadoc

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Or use Java 8 DateTimeFormatter :)

From the Javadoc

A formatter created from a pattern can be used as many times as necessary, it is immutable and is thread-safe.