I have tried below tests. But unable to parse the date format: 2020-04-19T19:00:54
why am I facing this issue?
public ZonedDateTime convert(Utf8 date) {
String datee = ((String) date.toString()).replace("T", " ")
LocalDateTime today = LocalDateTime.parse(datee, formatter)
ZonedDateTime currentISTime = today.atZone(ZoneId.systemDefault())
ZonedDateTime currentETime = currentISTime.withZoneSameInstant(ZoneId.systemDefault())
return ZonedDateTime.parse(formatter.format(currentETime), formatter)
}
String datee = ((String) date.toString()).replace("T", " ")
try{
var zoned = ZonedDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(datee.toString()))
return zoned.withZoneSameInstant(ZoneId.systemDefault())
} catch (DateTimeException e) {
//no time zone information -> parse as LocalDate
return ZonedDateTime.parse(datee.toString())
}
Exception:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-04-19 19:00:54' could not be parsed at index 10 at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:598)
at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:583)
DateTimeFormatter
to parse your Date-Time stringYou do not need a DateTimeFormatter
to parse your Date-Time string because your Date-Time string is already in ISO 8601 format.
The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter
object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
String strDateTime = "2020-04-19T19:00:54";
LocalDateTime ldt = LocalDateTime.parse(strDateTime);
System.out.println(ldt);
// Convert to ZonedDateTime using JVM's timezone
ZonedDateTime zdtSystem = ldt.atZone(ZoneId.systemDefault());
System.out.println(zdtSystem);
// Convert the ZonedDateTime to some other timezone e.g. Asia/Kolkata
ZonedDateTime zdtIndia = zdtSystem.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
System.out.println(zdtIndia);
}
}
Output on my system in Europe/London timezone:
2020-04-19T19:00:54
2020-04-19T19:00:54+01:00[Europe/London]
2020-04-19T23:30:54+05:30[Asia/Kolkata]
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.