Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将字符串转换为日期?_Java - Fatal编程技术网

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