-2
SimpleDateFormat df = new SimpleDateFormat();
Date lastLogin = null;
try {
    String troubleChild = lineScanner.next();
    lastLogin = df.parse(troubleChild);
} catch (ParseException e) {
    System.out.println("ohnoes");
}

Hi I'm quite new to using the date functions and I've come up with a problem. I have a file that is being parsed into various variables and they all work except this one i can never get it so that it passes the try/catch clause i've looked up similar problems but none of them work on my code.(The date i am inputting is in the format: Mon, Oct 30 22:20:11 GMT 2017) please can I get some help and thanks for it!

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • 1
    Since you’re new to date functions, I recommend you do not start out with the long outdated `Date` and `SimpleDateFormat`. There’s `java.time` also known as JSR-310, a modern Java date and time API that is much nicer to work with and comes with a lot fewer negative surprises. See [the Oracle tutorial](https://docs.oracle.com/javase/tutorial/datetime/) or find other tutorials out there. – Ole V.V. Nov 28 '17 at 08:51
  • 1
    I am quite surprised that none of the similar problems you found worked on your code. I invite you to explain what you tried and how it failed, and I’m sure we can help you better. – Ole V.V. Nov 28 '17 at 09:26
  • Please search Stack Overflow before posting. Parsing date-time strings has been addressed many hundreds, if not thousands, of times already on this site. – Basil Bourque Nov 28 '17 at 18:25

1 Answers1

1

Solution: java.time

Please don’t take the trouble with the long outmoded classes Date and SimpleDateFormat. Instead use java.time, the modern Java date and time API also known as JSR-310:

    DateTimeFormatter dtf 
            = DateTimeFormatter.ofPattern("E, MMM d H:mm:ss z uuuu", Locale.UK);
    String inputDate = "Mon, Oct 30 22:20:11 GMT 2017";
    ZonedDateTime lastLogin = ZonedDateTime.parse(inputDate, dtf);
    System.out.println(lastLogin);

This prints

2017-10-30T22:20:11Z[GMT]

Since dates and times may come in so many different textual formats, I am using a format pattern string to specify your particular format. For which letters you may use, and what difference it makes whether you use 1, 3 or 4 of the same letter, see the documentation. Beware that format pattern strings are case sensitive.

Problem: SimpleDateFormat

You used the no-arg SimpleDateFormat constructor. The way I read the documentation, this gives you the default date format for your locale. If your JVM is running UK locale, I believe the format goes like 28/11/17 10:57 — not much like the input format you were trying to parse. You can use System.out.println(df.format(new Date())); to find out. The usual SimpleDateFormat constructor to use would be SimpleDateFormat(String, Locale) so that you may again supply a format pattern string and a locale.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161