纵观通过Selenium读取整个表,并将结果写入到一个Excel文件,我目前面临的一个问题格式化/解析日期String的Date对象。我要存档的是以下格式:
dd-mm-yyyy
Run Code Online (Sandbox Code Playgroud)
从表中检索的 dateString 如下所示
16 APR 2020
Run Code Online (Sandbox Code Playgroud)
我尝试使用SimpleDateFormat格式化程序,但我得到了一个ParseException.
java.text.ParseException: Unparseable date: "16 Apr 2020"
Run Code Online (Sandbox Code Playgroud)
仅供参考:这是String当今解析和格式化日期的方法java.time(可从 Java 8 获得):
public static void main(String[] args) {
// the date String
String dateString = "16 Apr 2020";
/*
* which is parsed to a LocalDate using a formatter
* with a suitable pattern and a fitting Locale
* (ENGLISH is a good choice because it is language specific,
* you could use a country specific one here as well, like US or UK)
*/
LocalDate ld = LocalDate.parse(dateString,
DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH));
/*
* and which is then printed in a different format
* using a formatter with a different pattern
* (this time no Locale is needed because the format is numeric)
*/
System.out.println(ld.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")));
}
Run Code Online (Sandbox Code Playgroud)
这个的输出是
public static void main(String[] args) {
// the date String
String dateString = "16 Apr 2020";
/*
* which is parsed to a LocalDate using a formatter
* with a suitable pattern and a fitting Locale
* (ENGLISH is a good choice because it is language specific,
* you could use a country specific one here as well, like US or UK)
*/
LocalDate ld = LocalDate.parse(dateString,
DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ENGLISH));
/*
* and which is then printed in a different format
* using a formatter with a different pattern
* (this time no Locale is needed because the format is numeric)
*/
System.out.println(ld.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")));
}
Run Code Online (Sandbox Code Playgroud)