tl;dr
Instant.now().
.truncatedTo( ChronoUnit.MILLISECONDS ) ;
.toString()
2018-01-23T01:23:45.123Z
Thread-safety issue?
That is bizarre behavior I have not heard of. My first guess is a threading problem. The legacy date-time classes are not thread-safe. Their replacements, the java.time classes, are entirely thread-safe.
java.time
You could replace those troublesome old legacy classes. They were supplanted years ago in Java by the modern java.time classes. For Android, see bullets below.
Instant
The java.util.Date
class was replaced by java.time.Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Capture the current moment in UTC.
If you want only milliseconds, you can truncate any microseconds or nanoseconds that may be present in your Instant
.
Instant instantTruncated = instant.truncatedTo( ChronoUnit.MILLISECONDS ) ;
ISO 8601
Your desired output format is defined by the ISO 8601 standard.
The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
String output = instant.toString();
2018-01-23T01:23:45.123Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.