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

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

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, lets deal with this: yyyy-MM-ddTHH:mm:ss.SSSZ. The trailing Z is the interesting part. Usually theres 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-ddTHH:mm:ss.SSSZ, 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-ddTHH:mm:ss.SSSZ);
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-ddTHH:mm:ss.SSSZ and Java 8 you could do

String string = 2018-04-10T04:00:00.000Z;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy-MM-ddTHH:mm:ss.SSSZ, 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-ddTHH:mm:ss.SSSZ);
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
}

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

Leave a Reply

Your email address will not be published. Required fields are marked *