Java 如何将字符串转换为日期?
我不知道字符串的格式是什么 可能是Java 如何将字符串转换为日期?,java,Java,我不知道字符串的格式是什么 可能是2015-10-10或2015/10/10,也可能是2015-10-30 15:30 正则首先我想用它来判断是否是有效的日期或时间,然后用SimpleDataFormat解析,我应该做什么更好 所有格式包括: - 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 -
2015-10-10
或2015/10/10
,也可能是2015-10-30 15:30
正则首先我想用它来判断是否是有效的日期或时间,然后用SimpleDataFormat解析,我应该做什么更好
所有格式包括:
- 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
我用过这个。你可以试试看。它在maven central上提供。如果您正在使用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);
}
你最好对所有可能使用的格式有一些了解。如果没有,那么你就有麻烦了,你的代码也有麻烦了,。。。。这个问题也是如此。请参考可能会给你一些想法。谢谢,这个课程可以满足我的需要。谢谢更新信息。
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);
}
/**
* 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;
}