简体   繁体   中英

How to parse string timestamp to LocalDateTime

I am trying parse string timestamp to LocalDateTime .

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX");

String requestTimestamp = "2020-11-27 18:04:31+0";
String endDate ="2020-12-25 23:59:59+0";
final Long between = ChronoUnit.MINUTES.between(LocalDateTime.parse(endDate,formatter), LocalDateTime.parse(requestTimestamp,formatter));

Getting below exception:

Caused by: java.time.format.DateTimeParseException: Text '2020-12-25 23:59:59+0' could not be parsed at index 19
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)

Can any you please help me what is wrong in my code. Why I am getting DateTimeParseException ?

There are two issues with your code.

  1. As with your pattern, yyyy-MM-dd HH:mm:ss.SSSX , the input does not contain 2020-11-27 18:04:31+0 .SSS part (fraction-of-second)

  2. +0 in your input has to be +00 for Zone offset. If you are having zero as zone offset, make your input to be of form 2020-11-27 18:04:31Z with pattern yyyy-MM-dd HH:mm:ssX

Below is a working code,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX");

String requestTimestamp = "2020-11-27 18:04:31Z";
String endDate = "2020-12-25 23:59:59Z";

Adding two last cents, If you have control over input, it is always suggested to go with Predefined Formatters. I feel ISO_INSTANT will suit your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM