2

I have this exception with this code:

java.text.SimpleDateFormat@42ee54java.text.ParseException: Unparseable date: "Fri Dec 25 02:00:00 EET 2020"

@PostMapping
public ResponseEntity<?> addEvent(@Valid @RequestBody Event event) {
    try {
        SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        format1.parse(String.valueOf(event.getDate()));
        format1.setLenient(false);
        eventService.save(event);
        return new ResponseEntity<>(event, HttpStatus.CREATED);
    } catch (IllegalArgumentException | ParseException e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
}

Due to date format is defined correctly. What can be wrong here? Thanks in advance.

0xh3xa
  • 4,801
  • 2
  • 14
  • 28
Robert Gurjiev
  • 500
  • 1
  • 4
  • 17
  • thans to everybody! – Robert Gurjiev Mar 23 '20 at 13:49
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 23 '20 at 14:08
  • What is the type returned from `event.getDate()`? Asking because it may look like you are converting a `Date` to a `String` only to parse it back into a `Date`? – Ole V.V. Mar 23 '20 at 19:39

1 Answers1

3

You have to set Locale, like this:

SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);

because of Fri Dec in your input string and your default locale is probably not english

alex
  • 8,904
  • 6
  • 49
  • 75