如何正确设置 javafx datepicker 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36968122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:52:40  来源:igfitidea点击:

How to set javafx datepicker value correctly?

javajavafx

提问by Hussein Saied

I used this method to setting datepicker value but sometimes throw an exception:

我使用此方法设置 datepicker 值但有时会引发异常:

public static final LocalDate LOCAL_DATE (String dateString){
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    LocalDate localDate = LocalDate.parse(dateString, formatter);
    return localDate;
}

try {
        datePicker.setValue(LOCAL_DATE("2016-05-01");
    } catch (NullPointerException e) {
    }

//the exception:
java.time.format.DateTimeParseException: Text '' could not be parsed at index 0

So what's the wrong here?

那么这里有什么问题呢?

采纳答案by James_D

You specify a format for parsing the date of dd-MM-yyyy:

您指定解析日期的格式dd-MM-yyyy

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");

but then you provide the date in a format that doesn't match that:

但随后您以不匹配的格式提供日期:

datePicker.setValue(LOCAL_DATE("2016-05-01"));

Obviously, "2016-05-01"is not in the format "dd-MM-yyyy".

显然,"2016-05-01"不是格式"dd-MM-yyyy"

Try

尝试

datePicker.setValue(LOCAL_DATE("01-05-2016"));