Oliver
Oliver

Reputation: 23550

Java : Impossible to parse "23/10/1973" with "dd/MM/yyyy HH:mm" format

I'm trying to parse many string dates to Date(s), some with time part, others without, with the "dd/MM/yyyy HH:mm" format.

public static Date StringToDate (String format, String theDate) {

  SimpleDateFormat df = new SimpleDateFormat(format);

  Date retDate = null;
  try {
   df.setLenient(true);
   retDate = df.parse(theDate);
  } 
  catch (ParseException e) {
   e.printStackTrace();
  }

  return (retDate);
 }

(here, format is always "dd/MM/yyyy HH:mm").

But this causes an exception, even with setLenient forced at true. Do you know how I may convert to Date a lot of strings formatted like "dd/MM/yyyy HH:mm:ss", but with someones without time, some others without secondes, and still other one with everything ?

Upvotes: 0

Views: 434

Answers (2)

Mr. Shiny and New 安宇
Mr. Shiny and New 安宇

Reputation: 13898

If you know that some strings have a time and some don't, and there are no other cases, I'd just check the length of the string. However, if you have many different formats available, I'd try each one in some order that makes sense, until you get a valid date.

Upvotes: 1

Emmanuel
Emmanuel

Reputation: 17061

I always have two parse strings, and I parse twice; once with date/time and once with date only.

Upvotes: 0

Related Questions