-4
Unparseable date: "Tue Jul 03 16:59:51 IST 2018" Exception

String date="Tue Jul 03 16:59:51 IST 2018";

i want to parse it. My code is

SimpleDateFormat newformat=SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
Date d=newformat.parse(date);
Amrit kumar
  • 466
  • 6
  • 9
Jss
  • 41
  • 1
  • 5
  • 2
    hum, you do you expect your pattern to parse your string ? it's just impossible, string is *Day Month year*, and pattern is *year-month-day*, you should learn to build pattern – azro Jul 03 '18 at 09:35
  • 1
    Your pattern has to match the string you provide – XtremeBaumer Jul 03 '18 at 09:36
  • `SimpleDateFormat` looks at the first element of the format pattern string, `yyyy`, this means 4-digit year. Then it looks at the first element of your date string, `Tue`. `Tue` cannot be a four digit year. Therefore it throws the exception (it probably only needs to look at the `T` to decide). – Ole V.V. Jul 03 '18 at 13:51
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Jul 04 '18 at 08:33

2 Answers2

2

You are using old and quite problematic classes, especially Date.

For your example, perhaps consider using LocalDateTime

String date = "Tue Jul 03 16:59:51 IST 2018";
DateTimeFormatter format = DateTimeFormatter
        .ofPattern("EEE MMM dd HH:mm:ss z yyyy");
LocalDateTime dateTime = LocalDateTime.parse(date, format);
achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • I can’t decide whether I want to recommend `ZonedDateTime` over `LocalDateTime` here. The string includes a time zone abbreviation, so it could be considered a shame to throw it away from the outset. On the other hand, three and four letter time zone abbreviations are generally ambiguous, so if trying to parse it, we risk a result that conflicts with what was intended. `LocalDateTime` evades that problem. – Ole V.V. Jul 04 '18 at 10:47
  • 1
    @OleV.V. Funnily enough I wrote the answer initially with `ZonedDateTime` but edited it to `LocalDateTime`. – achAmháin Jul 04 '18 at 10:55
1

Since your pattern has to match the string you want to parse you need to adjust the pattern as following:

EEE MMM dd HH:mm:ss z yyyy

Infos gathered from the docs.

You should also use the new java.time API introduced with Java 8.

String s = "Tue Jul 03 16:59:51 IST 2018";
//Java 7 way
SimpleDateFormat newformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = newformat.parse(s);
//Java 8 way
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy");
LocalDateTime dateTime = LocalDateTime.parse(s, formatter);
XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65