Loss of Data
You are parsing a string input with six digits of fractional second, which means microsecond.
You are using the old java.sql.Date class which supports only milliseconds (3 digits). So even if you manage to parse that input, you will be losing some information.
java.time
The classes you are using, java.util.Date
& java.text.SimpleDateFormat
, have been supplanted by the new java.time framework built into Java 8 and later.
The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The java.time classes support nanosecond resolution, up to 9 digits of fractional second. So no loss of data given your inputs.
ISO 8601
Both of your String inputs are in the formats defined by the ISO 8601 standard.
The java.time classes use ISO 8601 by default when parsing or generating String representations of date-time values. So we can specify one of the predefined formatter rather than define a formatter pattern. For some formats we need not even bother specifying a formatter at all.
Example Code
You have two input strings, so two examples.
Example 1
The first string has no time zone or offset-from-UTC info. So we must specify a time by which to interpret the meaning of that input. I assume your intention was for UTC. We specify UTC as the time zone by calling withZone
.
That time zone is also assigned as the time zone of the ZonedDateTime
object. In other words, no further time zone adjustment is made.
String input = "2015-12-03T15:00:08.868987";
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone ( ZoneOffset.UTC );
ZonedDateTime zdt = ZonedDateTime.parse ( input , formatter );
zdt: 2015-12-03T15:00:08.868987Z
Example 2
Your second string does contain time zone information, in the form of a Z
which stands for Zulu
and means UTC
.
The java.time framework offers the Instant
class to represent a moment on the timeline in UTC. You can think of a ZonedDateTime
as being an Instant
plus a time zone (ZoneId
).
Because this second string is (a) in UTC time zone, and (b) in ISO 8601 format, we need not specify any formatter. The Instant
class can directly parse such a String.
String input = "2015-12-03T17:00:08Z";
Instant instant = Instant.parse ( input );
Dump to console.
System.out.println ( "instant: " + instant );
instant: 2015-12-03T17:00:08Z