Java:无法解析“23/10/1973”与“dd/MM/yyyy HH:mm”格式

发布于 2024-10-01 04:58:07 字数 536 浏览 9 评论 0原文

我正在尝试将许多字符串日期解析为日期,其中一些带有时间部分,另一些则没有,采用“dd/MM/yyyy HH:mm”格式。

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);
 }

(此处,格式始终为“dd/MM/yyyy HH:mm”)。

但这会导致异常,即使 setLenient 强制为 true。你知道我如何将许多格式如“dd/MM/yyyy HH:mm:ss”的字符串转换为日期,但有些人没有时间,有些人没有秒数,还有一个人有一切?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

也只是曾经 2024-10-08 04:58:08

我总是有两个解析字符串,并且解析两次;一次包含日期/时间,一次仅包含日期。

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

酒废 2024-10-08 04:58:07

如果您知道有些字符串有时间而有些没有,并且没有其他情况,我只会检查字符串的长度。但是,如果您有多种不同的格式可用,我会按某种有意义的顺序尝试每种格式,直到您获得有效的日期。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文