Parsing String to Date with DateTimeFormatter in java 8
Generally, we face two problems with dates
- Parsing String to Date
- 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(insta nt, zoneId);
System.out.println(dateTimeInT z.format(dtf));
Method 2:
Use DateTimeFormatter
built-in constants e.g ISO_INSTANT
to parse string to LocalDate
. ISO_INSTANT
can parse dates of pattern
yyyy-MM-dd’T’HH:mm:ssX e.g ‘
LocalDate parsedDate
= LocalDate.parse(dateString, DateTimeFormatter.ISO_INSTANT) ;
DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern(" yyyy MM dd");
System.out.println(parsedDate. format(displayFormatter));
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 DateTimeException
Since
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"));