Parsing String to Date with DateTimeFormatter in java 8

Parsing String to Date with DateTimeFormatter in java 8

Generally, we face two problems with dates

  1. Parsing String to Date
  2. Display Date in desired string format

DateTimeFormatter class in Java 8 can be used for both of these purposes. Below methods try to provide the solution to these issues.

Method 1: Convert your UTC string to Instant. Using Instant you can create Date for any time-zone by providing time-zone string and use DateTimeFormatter to format the date for display as you wish.

String dateString = "2016-07-13T18:08:50.118Z";
String tz = "America/Mexico_City";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
ZoneId zoneId = ZoneId.of(tz);

Instant instant = Instant.parse(dateString);

ZonedDateTime dateTimeInTz =ZonedDateTime.ofInstant(instant, zoneId);

Method 2:

Use DateTimeFormatter built-in constants e.g ISO_INSTANT to parse string to LocalDateISO_INSTANT can parse dates of pattern

yyyy-MM-dd’T’HH:mm:ssX e.g 2011-12-03T10:15:30Z’

LocalDate parsedDate
  = LocalDate.parse(dateString, DateTimeFormatter.ISO_INSTANT);

DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("yyyy MM dd");

Method 3:

If your date string has much precision of time e.g it captures the fraction of seconds as well as in this case 2016-07-13T18:08:50.118Z then method 1 will work but method 2 will not work. If you try to parse it will throw DateTimeException Since ISO_INSTANT formatter will not be able to parse fraction of seconds as you can see from its pattern. In this case, you will have to create a custom DateTimeFormatter by providing date pattern as below.

LocalDate localDate 
= LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));


Leave a Reply to Sudhir Mishra Cancel reply

Please enter your comment!
Please enter your name here