开发者

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 th开发者_Go百科eDate) {

  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 ?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜