Java SQL date is off by 1 day

前端 未结 2 1435
故里飘歌
故里飘歌 2021-01-22 20:57

I\'m using a MySQL server which is located in the same timezone as me. Im trying to insert a java.util.Date into the database on a column of type DATE with the foll

2条回答
  •  走了就别回头了
    2021-01-22 21:10

    For a date-only value, without time-of-day and without time zone, you should be using the MySQL type DATE when defining your column. This type matches the DATE type defined in the SQL standard.

    On the Java side, never use java.util.Date. That class is part of the terrible date-time classes bundled with the earliest versions of Java. They were years ago supplanted by the java.time classes defined in JSR 310.

    For a date-only value in Java, use java.time.LocalDate.

    In your map, you should be storing LocalDate object rather than mere string. But if you must, you can parse and generate strings. The format of your strings appear to coincide with the standard format defined in ISO 8601. The java.time classes use those standard formats by default. So no need to specify a formatting pattern.

    LocalDate localDate = LocalDate.parse( "2021-01-23" ) ;
    

    Objects of the java.time classes can be exchanged with your database by using a JDBC driver compliant with JDBC 4.2 and later.

    Write that to the database.

    myPreparedStatement.setObject( … , localDate ) ;
    

    Retrieve from database.

    LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
    

    Using the approach shown above makes time zones irrelevant: LocalDate via JDBC 4.2 or later on a column of type MySQL DATE — That is, unless your JDBC driver is buggy (Bug #30877755): See Answer by Teh Swish.

提交回复
热议问题