【问题标题】:Parsing specific String to Date [closed]将特定字符串解析为日期 [关闭]
【发布时间】:2020-03-20 10:30:54
【问题描述】:

通过 Selenium 读取整个表格并将结果写入 excel 文件,我目前在Date 对象中格式化/解析日期String 时遇到问题。我要归档的是以下格式:

dd-mm-yyyy

从表中检索到的日期字符串如下所示

16 APR 2020

我尝试使用SimpleDateFormat 格式化程序,但我得到了ParseException

java.text.ParseException: Unparseable date: "16 Apr 2020"

【问题讨论】:

  • 你是如何尝试的?你可以发布代码吗?提示:您想要的格式有缺陷...m 表示分钟,M 表示月份。
  • 您是否必须使用SimpleDateFormatDate 或者您是否可以决定采用称为java.time 的不太麻烦的方式?
  • 仅供参考,您使用的日期时间类在几年前被 JSR 310 中定义的现代 java.time 类所取代。

标签: java date parsing


【解决方案1】:

仅作记录:这是当今如何使用 java.time 解析和格式化日期 String(可从 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")));
}

这个输出是

16-04-2020

【讨论】:

  • @Eltomon,仅供参考,如果日期不正确,则不会失败。例如31 Apr 2020 将打印30-Apr-2020。如果您使用SimpleDateFormat,则相同的值将打印为01-May-2020
  • @OleV.V.是的,谢谢...这个例子在用于解析的格式化程序中使用Locale 更好。
【解决方案2】:

执行以下操作

     Date date = new SimpleDateFormat("dd MMM yyyy").parse("16 aug 2020");
     System.out.println(date);

输出 2020 年 8 月 16 日星期日 00:00:00 PDT

您收到错误的原因是 dd-mm-yyyy 与“2020 年 8 月 16 日”不匹配 后面没有连字符,月份有三个字母,mm只代表两个,dd-mm-yyyy是一种正则表达式,应该匹配要解析的字符串

【讨论】:

  • 我觉得应该是三倍M。new SimpleDateFormat("dd MMM yyyy")
  • 你说得对,谢谢,我用 2 M 测试它然后忘了放回去,顺便说一句,2 M 中有错误
  • 正确答案,但恕我直言,我们不应该帮助人们使用早已过时且臭名昭著的麻烦 SimpleDateFormat 类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。
  • @OleV.V.同意,但我不知道他是否有 java 8,而且我对他可能已经知道的事情有所帮助,他应该自己学习 time 包
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多