java.time
The modern Date-Time API, released with Java-8 in March 2014, supplanted the legacy date-time API (the java.util
Date-Time API and their formatting API, SimpleDateFormat
). Since then, it is strongly recommended to stop using the error-prone legacy API and switch to java.time
API.
Solution using java.time
API: java.time
API is based on ISO 8601 and therefore you do not need a DateTimeFormatter
to parse a date-time string which is already in ISO 8601 format (e.g. your date-time string, 1993-06-08T18:27:02.000Z
).
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
class Main {
public static void main(String[] args) {
String strModifiedDate = "1993-06-08T18:27:02.000Z";
Instant instant = Instant.parse(strModifiedDate);
System.out.println(instant);
// It can also be directly parsed into a ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.parse(strModifiedDate);
System.out.println(zdt);
// or even into an OffsetDateTime
OffsetDateTime odt = OffsetDateTime.parse(strModifiedDate);
System.out.println(odt);
}
}
Output:
1993-06-08T18:27:02Z
1993-06-08T18:27:02Z
1993-06-08T18:27:02Z
If for any reason, you need java.util.Date
instance, you can get it as follows:
Date date = Date.from(instant);
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness:
Here is the solution using the legacy date-time API. First of all, note that 'Z' is not the same as Z. 'Z'
is just a character literal whereas Z
is the timezone designator for zero-timezone offset (or UTC). So, never use 'Z'
in the date-time formatting/parsing pattern; otherwise, it will be interpreted merely as a literal character, and not as a timezone designator.
The correct letter to be used in the pattern for timezone offset is X
.
Demo:
class Main {
public static void main(String[] args) throws ParseException {
String strModifiedDate = "1993-06-08T18:27:02.000Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date modifiedDate = sdf.parse(strModifiedDate);
System.out.println(modifiedDate);
}
}