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?
CodePudding user response:
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 double
s 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.
CodePudding user response:
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);
}