How do I convert 2018-04-10T04:00:00.000Z string to DateTime? [duplicate] How do I convert 2018-04-10T04:00:00.000Z string to DateTime? [duplicate] java java

How do I convert 2018-04-10T04:00:00.000Z string to DateTime? [duplicate]


Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);String formattedDate = outputFormatter.format(date);System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");String formattedDate = outputFormat.format(date);System.out.println(formattedDate); // prints 10-04-2018


Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);LocalDate date = LocalDate.parse(string, formatter);System.out.println(date);

Update:For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {        compile 'joda-time:joda-time:2.9.4'}