如何将字符串转换为日期?

3

我不知道什么是格式化字符串。

它可能是2015-10-102015/10/10,也可能是2015-10-30 15:30

首先,我想使用正则表达式判断日期或时间是否有效,然后再使用SimpleDateFormat进行解析,应该怎么做才更好?

所有格式包括:

- yyyy-MM-dd
- yyyy.MM-dd
- yyyy/MM/dd
- yyyy-MM-dd HH24:mm
- yyyy.MM-dd HH24:mm
- yyyy/MM/dd HH24:mm
- yyyy-MM-dd HH24:mm:ss
- yyyy.MM-dd HH24:mm:ss
- yyyy/MM/dd HH24:mm:ss

3
最好你对可能使用的所有格式有一些了解。如果没有,你会遇到麻烦,你的代码也会遇到麻烦......这个问题也一样。 - Hovercraft Full Of Eels
1
请参考http://viralpatel.net/blogs/check-string-is-valid-date-java/,也许可以给您一些想法。 - Dev
谢谢,这个类可以满足我的需求。 - biezhi
感谢提供最新信息。 - Hovercraft Full Of Eels
2个回答

1
use following date formatter to convert the date to String.
String d="2015-05-12";
DateFormat formatter  = new SimpleDateFormat("yyyy-mm-dd");
Date a=formatter.parse(d);

1
我已经使用Natty Date Parser。你可以在这里试用它。它可以在maven中央库这里下载。如果你正在使用gradle:
compile 'com.joestelmach:natty:0.12'

使用示例:

String[] exampleDates = {
    "2015-10-10",
    "2015/10/10",
    "2015-10-30 15:30"
};

Parser parser = new Parser();
for (String dateString : exampleDates) {
  List<DateGroup> dates = parser.parse(dateString);
  Date date = dates.get(0).getDates().get(0);
  System.out.println(date);
}

输出:

2015年10月10日周六PDT时间20:51:10

2015年10月10日周六PDT时间20:51:10

2015年10月30日周五PDT时间15:30:00


编辑:

如果您了解日期格式,则下面的StackOverflow比将依赖项添加到您的项目中要更好:

https://dev59.com/mm865IYBdhLWcg3wBJ4q#4024604


以下静态实用方法可能足够:
/**
 * Parses a date with the given formats. If the date could not be parsed then {@code null} is
 * returned.
 *
 * @param formats the possible date formats
 * @param dateString the date string to parse
 * @return the {@link java.util.Date} or {@code null} if the string could not be parsed.
 */
public static Date getDate(String[] formats, String dateString) {
  for (String format : formats) {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
      return sdf.parse(dateString);
    } catch (ParseException ignored) {
    }
  }
  return null;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接