【发布时间】:2020-06-22 00:14:03
【问题描述】:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class demo {
public static void main(String args[]) throws ParseException {
DateFormat date=new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
System.out.println(date.parse("18-09-2017")); //Doesn't give an error but output is incorrect
System.out.println(date.parse("2017-09-18")); //Output is correct.
}
}
如何以不同的方式解析两个包含日期的字符串。 注意:我需要 java.util.Date 类型的 parse 输出。
【问题讨论】:
-
所以你需要单独的格式化程序,你可以尝试用一个解析然后输入字符串,它失败了,使用另一个
-
date.parse(...) 对两者都适用。它不会给出任何错误,但输出不正确。问题是这个解析器不会失败。如果是这样,我可以用 catch 块中的其他格式化程序解析它,但它不会失败。但是输出不正确。
-
如果您“绝对,必须,毫无疑问”使用 Java 7 或更低版本,那么您可以使用
date.setLenient(false);强制格式化程序对其解析过程更加严格
标签: java datetime simpledateformat date-format date