Localdate.format,格式未应用

时间:2018-05-22 07:25:15

标签: java date javafx datepicker fxml

我的FXML中有一个DatePicker,我需要将Date插入到我的SQL数据库中。我想格式化我的日期,但它不起作用。

    LocalDate localDate = purchased_at.getValue();
    localDate.format(DateTimeFormatter.ofPattern("dd.mm.yyyy"));

这是我得到的错误。

Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: MinuteOfHour

我还是个初学者。我过去3或4个月就有Java了。我正在努力改进。

2 个答案:

答案 0 :(得分:2)

请勿格式化插入SQL数据库的日期。假设您的数据库列具有数据类型date并且您至少使用Java 8且至少使用JDBC 4.2,只需将LocalDate传递给您的PreparedStatement

    PreparedStatement insertStmt = myConnection.prepareStatement(
            "insert into my_table(purchase_date) values (?)");
    insertStmt.setObject(1, purchaseDate);

您的JDBC驱动程序将负责其余部分。如果使用JPA,您的JPA实现也会处理它。

如果您的列具有char类型(例如varchar(10))并且您无法更改它,请不要为其创建自己的格式。将日期存储为ISO 8601格式。 LocalDate.toString()生成此格式。

    String formattedDate = purchaseDate.toString();
    System.out.println(formattedDate);

在我的案例中输出是:

  

2017年11月29日

另外,为了向用户展示,您也不应该发明自己的格式。而是依赖于Java中的内置格式。例如:

    Locale turkish = Locale.forLanguageTag("tr");
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(turkish);
    String formattedDate = purchaseDate.format(dateFormatter);
    System.out.println(formattedDate);

输出:

  

2017年11月29日

您的代码出了什么问题?

有两件事是错的:

  1. 您使用的是小写mm。这意味着分钟,因为LocalDate没有时间,所以它抛出了你看到的异常。你得到的信息非常精确:

      

    不支持的字段:MinuteOfHour

    相反,您可以将大写MM用于两位数的月份。

  2. 您需要选择String方法返回的format格式。 LocalDate是不可变的,因此不受方法调用的影响。它也不能有格式。这只是日历中的日期。

  3. 链接: Wikipedia article: ISO 8601

答案 1 :(得分:1)

我必须为我的Datepicker使用String转换器。

    public String changeformat(DatePicker date) {

    date.setConverter(new StringConverter<LocalDate>() {
        String pattern = "MM.yyyy";
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

        {
            date.setPromptText(pattern.toLowerCase());
        }

        @Override
        public String toString(LocalDate date) {
            if (date != null) {
                return dateFormatter.format(date);
            } else {
                return "";
            }
        }

        @Override
        public LocalDate fromString(String string) {
            if (string != null && !string.isEmpty()) {
                return LocalDate.parse(string, dateFormatter);
            } else {
                return null;
            }
        }
    });
    return null;
}

它工作得非常好。我不得不使用一个参数,因为我目前正在使用5个Datepickers。