Reputation: 5136
I'm attempting to do something extremely simple - take the current date and time, and parse it in the desired format.
private final String datePattern = "yyyy:DDD";
private final String timePattern = "hh:mm:ss";
public void setDateAndTime(){
// Default constructor initializes to current date/time
Date currentDateAndTime = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);
SimpleDateFormat timeFormatter = new SimpleDateFormat(timePattern);
try {
this.date = dateFormatter.parse(currentDateAndTime.toString());
this.time = timeFormatter.parse(currentDateAndTime.toString());
} catch (ParseException e){
System.out.println("Internal error - unable to parse date/time");
System.exit(1);
}
}
This results in an exception:
Unparseable date: "Sat Nov 06 11:04:22 EDT 2010"
This is a perfectly valid date string, and the patterns I am using to initialize the SimpleDateFormat seem to be correct.
How can this error be avoided, and how can the SimpleDateFormat
be initialized as above?
Upvotes: 0
Views: 1499
Reputation: 1296
you code should be
SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);
SimpleDateFormat timeFormatter = new SimpleDateFormat(timePattern);
System.out.println(dateFormatter.format(currentDateAndTime));
Simply put, you cannot format a date object unless the output is a string
Upvotes: 0
Reputation: 597234
Date
from a String
String
from a Date
You need the latter - so use formatter.format(currentDateAndTime)
You are getting the exception, because you transform your Date
to String
by toString()
which you later try to parse, but which does not follow the format you've specified.
Upvotes: 4