0

Trying to convert string to localDateTime and see if the date is older than a year. I know it should work but it's not working. Getting parsing exceptions at index 'i'

LocalDateTime currentTimeLastYear = LocalDateTime.now().minusYears(1);

String pattern = "MM/dd/yyyy'T'HH:mm:s";

// ex "8/30/2019T15:51:5"
String queryToDate = query.getDateRange().getToDate();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
LocalDateTime localDateTime = LocalDateTime.parse(queryToDate, formatter);
System.out.println(localDateTime);

if(localDateTime.isBefore(currentTimeLastYear)) {
    return true;
}    
Gunther
  • 13
  • 5

1 Answers1

0

Use a single letter in your formatting pattern for each part where single-digit number values omit a padding zero.

If month 8 rather than 08, use M rather than MM.

This is explained in the Javadoc documentation:

If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.

String input = "8/23/2021T1:23:7"
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu'T'H:m:s" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

See this code run live at IdeOne.com.

ldt.toString() = 2021-08-23T01:23:07

Tip: Educate the publisher of your data about compliance with ISO 8601 and always using the padding zero. Your input appears to be using a screwed-up attempt at ISO 8601.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Got it. I'm fairly new to java. Quick question if you don't mind: using a single letter does work as you explained, but will it exclude milliseconds if they are present and pattern "M/d/uuuu'T'H:m:s": 2020-12-14T23:38:46.269 – Gunther Dec 15 '20 at 04:49
  • @Gunther You don’t mention any fraction of a second in your Question. You really should give example input there. – Basil Bourque Dec 15 '20 at 04:50
  • I'll try to look it up first and then ask. I was just curious about it. You've answered my original question. Thank you – Gunther Dec 15 '20 at 04:54
  • @Gunther Search before posting. Most every basic question on date-time handling has already been asked and answered many times on Stack Overflow. – Basil Bourque Dec 15 '20 at 04:57