Home > Net >  convert iso to utc format in java
convert iso to utc format in java

Time:05-02

I'm getting below exception while converting date string from ISO to UTC format in java, what I'm doing wrong here? Please find my code below:

Test.java

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class Test {
    public static void main(String[] args) {
        String date="2020-11-02T07:00:00.114";
        String result = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")).atOffset(ZoneOffset.UTC).toString();
        System.out.println("result: " result);
    }
}

Exception:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-11-02T07:00:00.114' could not be parsed, unparsed text found at index 19
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at test.service.Test.main(Test.java:11)

CodePudding user response:

Your pattern ends in ss, in other words: In seconds. Your input then has still more stuff.

DateTimeFormatter doesn't take a wild stab at it - it either matches properly or it does not parse. It looks like those are intended to be milliseconds; toss .SSS at the end of your pattern.

CodePudding user response:

You are giving the format of:

yyyy-MM-dd'T'HH:mm:ss

However are specifying a string with fractions of a second 2020-11-02T07:00:00.114.

That is parsing whole seconds, but there is still more in the time string.

You need format of:

yyyy-MM-dd'T'HH:mm:ss.SSS

  • Related