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

SyntaxFix
1 min readFeb 9, 2022

What is the actual problem ?

I get a date from a JSON API which looks like this “2018–04–10T04:00:00.000Z”. I want to convert it in order to obtain a Date or String object and get something like “01–04–2018” that its “dd-MM-YYYY”. How can I do it?

The Solution for above problem is below

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

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);

Give a Clap and Follow SyntaxFix for more answers to questions like this.

--

--

SyntaxFix

Curated Solutions On Popular Questions — On All Programming Languages, Cloud Computing, Tools etc