Java 9 how to convert LocalDateTime and ZonedDateTime
Recently I needed to converted unusual formatted date in Java 9:
"dateTime" -> "2017-11-23T17:00:00-0700"
In the past I was using SimpleDateFormat and it was doing very good job. But since java 8 I found that it can be used: LocalDateTime and ZonedDateTime. Another problem that I faced is error when the date was serialized to MySQL:
- Field error in object 'MyDate' on field 'dateTime': rejected value [2017-11-23T17:00:00-0700]; codes [MyDate.dateTime.typeMismatch.error...default message [Unparseable date: "2017-11-23T17:00:00-0700"]
Below is sample code in Java / Groovy:
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import java.time.ZonedDateTime
import java.text.SimpleDateFormat;
//facebook date
String start_time = "2017-11-23T17:00:00-0700"
//
// Using SimpleDateFormat - no tread safe
//
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = dateFormat.parse(start_time);
dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
String formatedDate = dateFormat.format(date);
System.out.println(formatedDate)
//2017-11-24 02:00
//
// Using LocalDateTime - no offset second and no time zone
//
String now = start_time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
LocalDateTime formatDateTime = LocalDateTime.parse(now, formatter);
System.out.println("Before : " + now);
System.out.println("After : " + formatDateTime);
// System.out.println("After : " + formatDateTime.format(formatter));
//Before : 2017-11-23T17:00:00-0700
//After : 2017-11-23T17:00
//
// Using ZonedDateTime - no offset second and no time zone
//
DateTimeFormatter formatterZ = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
ZonedDateTime formatDateTimeZ = ZonedDateTime.parse(now, formatter);
System.out.println("Before : " + now);
System.out.println("After : " + formatDateTimeZ);
System.out.println("After : " + formatDateTimeZ.format(formatterZ));
//Before : 2017-11-23T17:00:00-0700
//After : 2017-11-23T17:00-07:00
//After : 2017-11-23T17:00:00-0700
//
// Using ZonedDateTime to Date
//
System.out.println(Date.from(formatDateTimeZ.toInstant()));
//Fri Nov 24 02:00:00 EET 2017
More on Java date conversion:
Java 9 java.text.ParseException: Unparseable date