Juan.carlos Juan.carlos - 1 year ago 69
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);

came as
- interesting part is June 31st.

Any clue?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download