0

I'm trying to move some processing from SimpleDateFormat to the new java.time packages.

In the following example:

final String str = "28/11/2016 11:58:51 AM UTC (date)";
final String format = "dd/MM/yyyy hh:mm:ss a z";
System.out.println(new SimpleDateFormat(format).parseObject(str));
System.out.println(LocalDateTime.parse(str, DateTimeFormatter.ofPattern(format)));

SimpleDateFormat parses the String, but LocalDateTime throws a DateTimeParseException.

The part in brackets is variable, so SimpleDateFormat's approach works well. Is there a way of making LocalDateTime have this behaviour?

Jakg
  • 922
  • 12
  • 39
  • On my machine, `SimpleDateFormat` cannot parse the string either... Why don't you just extract the relevant part from the string before parsing it? – Sweeper Jun 14 '19 at 15:35
  • You can try using DateTimeFormatterBuilder class of java.time.format package for this, it provides a lot of flexibility in defining the patterns. DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern(format) .appendLiteral(" (date)").toFormatter(); – Pallavi Sonal Jun 14 '19 at 15:45
  • @Sweeper Isn’t that a locale problem? As I think you know, `AM` is English and cannot be parsed in a locale with a different language. – Ole V.V. Jun 15 '19 at 14:07
  • 1
    @PallaviSonal If the postfix is always ` (date)`, parsing it as literal text is a good idea, also for validation. You don't need a builder for that. We can just enclosexthe literal text in single quotes in the format pattern string. – Ole V.V. Jun 16 '19 at 05:13

0 Answers0