I have a method that has a parameter annotated with @DateTimeFormat.
public static void exampleMethod(@ApiParam(value = "date", required = true)
@DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {...}
When it gets "2021-05-13", date variable contains "2021-05-12" for some reason. What other similar annotations or date data types I can use to avoid this bug?
Thank in advance.
CodePudding user response:
java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
A java.util.Date
object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, it is the JVM's timezone that gets applied by default, which could be the root cause of the problem in your case.
Solution using java.time
, the modern Date-Time API: Change the type of date
field to LocalDate
as follows:
public static void exampleMethod(
@ApiParam(value = "date", required = true)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {...}
Learn more about the modern Date-Time API from Trail: Date Time.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.