Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

java - Localdate.format, format is not applied

I have a DatePicker in my FXML and I need the Date to insert it into my SQL-Database. I want to format my Date but it doesn't work.

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

This is the Error I get.

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

I'm still kind of a beginner. I had Java for the past 3 or 4 months now. I'm trying my best to improve.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don’t format your date for insertion into your SQL database. Assuming that your database column has datatype date and you are using at least Java 8 and at least JDBC 4.2, just pass the LocalDate to your PreparedStatement as it is:

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

Your JDBC driver will take care of the rest. If using JPA, your JPA implementation will take care of it too.

If your column has char type (for example varchar(10)) and you cannot change it, don’t invent your own format for it. Store the date in ISO 8601 format. LocalDate.toString() produces this format.

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

In my case output was:

2017-11-29

As an aside, for presentation to your user you shouldn’t invent your own format either. Rather rely on the built-in formats in Java. For example:

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

Output:

29.11.2017

What went wrong in your code?

There are two things wrong:

  1. You used lowercase mm. This means minute of hour, and since a LocalDate doesn’t have a time of day in it, it threw the exception you saw. The message you got is pretty precise:

Unsupported field: MinuteOfHour

Instead you may use uppercase MM for two-digit month.

  1. You need to pick up the format in the String returned from the format method. The LocalDate is immutable and therefore not affected by the method call. Also it cannot have a format in it. It’s just a date in the calendar.

Links


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...