【问题标题】:How can I fix string to date error simpledateform [duplicate]如何修复字符串到日期错误 simpledateform [重复]
【发布时间】:2021-01-18 06:05:45
【问题描述】:
String from = "2019.03.03";
SimpleDateFormat fDate = new SimpleDateFormat("yyyy.MM.dd"); 
Date n = fDate.parse(from);

这行有未处理的异常类型 ParseException "fDate.parse(from)"

如何修复此代码

【问题讨论】:

  • 在此代码周围添加一个 try-catch 块。
  • 另一个线程使用 Thread.sleep,而不是 SimplateDateFormat#parse,但它们都产生相同的编译器错误。
  • 哦,请使用DateTimeFormatterjava.time 包中的其他类,而不是已过时的SimpleDateFormatDateThis is why.

标签: java


【解决方案1】:

错误表明我们需要处理“如果”抛出解析异常。 要处理异常,我们可以使用 try-catch 块,如下所示:

try {
    String from = "2019.03.03";
    SimpleDateFormat fDate = new SimpleDateFormat("yyyy.MM.dd"); 
    Date n = fDate.parse(from);
    System.out.println(n);  
} catch(ParseException ex) {
    ex.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 2018-04-20
    • 2013-09-17
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多