【问题标题】:LGoodDatePicker issues with getDate()LGoodDatePicker 与 getDate() 的问题
【发布时间】:2021-06-15 22:54:53
【问题描述】:

我将 LGoodDatePicker 与 Apache NetbeansIDE 12.2 (https://github.com/LGoodDatePicker/LGoodDatePicker) 一起使用,我需要以 YYYY-MM-DD 格式获取日期。我正在使用此代码:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(datePicker1.getDate());

但我收到此错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Date

有什么建议吗?谢谢。

【问题讨论】:

    标签: java swing date netbeans datepicker


    【解决方案1】:

    这个DatePicker的方法getDate()返回一个java.time.LocalDate不是一个java.util.Date。这实际上是错误消息告诉您的内容,它需要 java.util.Date,但还有其他内容。
    这意味着您不应该尝试使用java.text.SimpleDateFormat 对其进行格式化,在这里使用java.time.format.DateTimeFormatter

    String date = datePicker1.getDate().format(DateTimeFormatter.ISO_LOCAL_DATE);
    

    或者使用DateTimeFormatter的方法ofPattern(String pattern)定义自定义模式:

    String date = datePicker1.getDate().format(DateTimeFormatter.ofPattern("uuuu-MM-dd");
    

    在这种情况下,您甚至可以使用LocalDatetoString() 方法来获得所需格式的String

    String date = datePicker1.getDate().toString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 2014-02-02
      相关资源
      最近更新 更多