gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:37 24 4
gpt4 key购买 nike

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

可能是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

最佳答案

我用过 Natty Date Parser为了这。你可以试试here .它在 Maven 中心可用 here .如果您使用的是 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);
}

输出:

Sat Oct 10 20:51:10 PDT 2015

Sat Oct 10 20:51:10 PDT 2015

Fri Oct 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;
}

关于java - 如何将字符串转换为日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34447041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com