0

I want to parse a java.util.Date from a String. I tried the following code but got unexpected output:

Date getDate() {
    Date date = null;

    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd");
    try {
        date = sdf.parse("Sat May 11");
    } catch (ParseException ex) {
        Logger.getLogger(URLExtractor.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

    return date;
}

When I run the above code, I got the following output:

Mon May 11 00:00:00 IST 1970
4
  • What were you expecting? Commented May 23, 2010 at 10:17
  • Because what output did you expect/want? Commented May 23, 2010 at 10:21
  • I was expecting "Sat" instead of "Mon". Commented May 23, 2010 at 10:25
  • Then you have to specify the year, you can't get a Saturday if that date is a Monday. Commented May 23, 2010 at 10:26

3 Answers 3

6

You have not specified a year in your string. The default year is 1970. And in 1970 the 11th of May was a Monday - SimpleDateFormat is simply ignoring the weekday in your string.

From the javadoc of DateFormat:

The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.

Sign up to request clarification or add additional context in comments.

Comments

0

Specify a year within the Format to get the correct output.

If you don't specify any year, the default is 1970.

Comments

0

if the year is the problem you can add y for year:

 public Date getDate() {
    Date date = null;

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd y");
    try {
        date = sdf.parse("May 11 2010");
    } catch (ParseException ex) {
        Logger.getLogger(URLExtractor.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

    return date;
}
 System.out.println(getDate());

Tue May 11 00:00:00 EDT 2010

Edit:

To get the correct day of the week you need to specify the date (with the year). I edited the code above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.