Reputation: 34803
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
Upvotes: 0
Views: 1481
Reputation: 55458
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.
Upvotes: 0
Reputation: 466
Specify a year within the Format to get the correct output.
If you don't specify any year, the default is 1970.
Upvotes: 0
Reputation: 39753
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.
Upvotes: 6