rybosome
rybosome

Reputation: 5136

SimpleDateFormat with a pattern results in error Unparseable Date

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

Answers (2)

mezzie
mezzie

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

Bozho
Bozho

Reputation: 597234

  • parsing is getting a Date from a String
  • formatting is getting a 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

Related Questions