Java 9 java.text.ParseException: Unparseable date

In this post:

  • java error Unparseable date
  • code example parsing:
    • Wed Nov 08 01:35:23 EET 2017

Parsing dates in java is a simple task if you know the input format. Sometimes you can end with errors like:

  • java.time.format.DateTimeParseException: Text 'Wed Nov 08 01:35:23 EET 2017' could not be parsed at index 0
  • java.text.ParseException: Unparseable date: "xWed Nov 08 01:35:23 EET 2017"

In order to parse those cases I use small method:

Date anyStringDateToDate(String anyDate) {
		Date date
		Boolean error = false

		// parse 2017-11-23T17:00:00-0700

		try {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
			ZonedDateTime formatDateTime = ZonedDateTime.parse(facedate, formatter);
			date = Date.from(formatDateTime.toInstant())
		} catch (Exception eZ) {
			error = true
		}
		if (error) {
			// parse Wed Nov 08 01:35:23 EET 2017
			try {
				SimpleDateFormat formatter = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
				date = (Date) formatter.parse(facedate);
			} catch (Exception eS) {
			}
		}
		return date
	}

More on Java date conversion:
Java 9 how to convert LocalDateTime and ZonedDateTime