[英]How to convert a string to a Date?
我不知道格式字符串是什么
可能是2015-10-10
或2015/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
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);
我已经使用了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);
}
输出:
10月10日星期六20:51:10 PDT 2015
10月10日星期六20:51:10 PDT 2015
10月30日星期五15:30:00 PDT 2015
编辑:
如果您知道日期格式,那么以下StackOverflow将比向项目添加依赖项更好:
https://stackoverflow.com/a/4024604/1048340
以下静态实用程序方法可能就足够了:
/**
* 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.