1

I want to parse LocalDateTime 2021-11-24T15:11:38.395 to LocalDateTime 2021-11-24T15:11:38.39. But LocalDateTime.parse() always adds zero in the end, ignoring my pattern.

public class DateTimeFormatUtils {
    private static final String ISO_DATE_TIME = "yyyy-MM-dd'T'HH:mm:ss.SS";

    public static LocalDateTime formatToISO(final LocalDateTime localDateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(ISO_DATE_TIME);
        return LocalDateTime.parse(formatter.format(localDateTime), formatter);
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        System.out.println(formatToISO(now));
    }

}

Output:

2021-11-30T11:48:28.449195200
2021-11-30T11:48:28.440

Is there way to deal with this problem?

SorryForAsking
  • 323
  • 2
  • 18
  • 3
    What you are looking for is a specific _format_ of a local date time (i.e. a string), not a `LocalDateTime`. It's like asking "how do I get a `double` to represent `5`? I always get `5.0`" – Sweeper Nov 30 '21 at 09:57
  • Hm, ok, I got you – SorryForAsking Nov 30 '21 at 10:05
  • Does this answer your question? [Java Instant to LocalDateTime trailing zero](https://stackoverflow.com/questions/53314552/java-instant-to-localdatetime-trailing-zero). Also related: [Problem converting string to LocalDateTime \[duplicate\]](https://stackoverflow.com/questions/70122794/problem-converting-string-to-localdatetime). – Ole V.V. Nov 30 '21 at 13:51

2 Answers2

4

Note that the strings "2021-11-24T15:11:38.39" and "2021-11-24T15:11:38.390" represent the same LocalDateTime. Technically, you've already got your expected output!

Since you say that the output is not what you expect, you are actually expecting a String as the output, since "2021-11-24T15:11:38.39" and "2021-11-24T15:11:38.390" are different strings. formatToISO should return a string - you should not parse the formatted date back to a LocalDateTime:

public static String formatToISO(final LocalDateTime localDateTime) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(ISO_DATE_TIME);
    return formatter.format(localDateTime);
}

This is similar to the common mistake of beginners printing out doubles and expecting the specific format they have used to assign to the variable to come out.

double d = 5;
System.out.println(d); // expected 5, actual 5.0

LocalDateTime, just like double, doesn't store anything about how it should formatted. It just stores a value, and the same value will be formatted the same way.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Java fraction-of-seconds is always return 3 digits.

Work around is, first convert LocalDateTime to String, then remove last character of the string.

Off course, please validate null checks.

private static String removeLastDigit(String localDateTime) {
        return localDateTime.substring(0, localDateTime.length()-1);
 }
Uday
  • 149
  • 6