This guide addresses the challenge of accurately inserting dates in "EEE MMM dd HH:mm:ss ZZZ yyyy" format into a MySQL database using java.sql.Date
. A common pitfall is using methods that lead to incorrect date values despite lacking explicit errors.
The recommended solution utilizes the robust java.time
package:
<code class="language-java">LocalDate date4 = ZonedDateTime .parse(date, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH)) .toLocalDate(); java.sql.Date date5 = java.sql.Date.valueOf(date4);</code>
This code efficiently parses the date string, handling time zone information correctly, and converts it to a LocalDate
before finally creating a java.sql.Date
suitable for database insertion.
Key Considerations:
Locale
(here, Locale.ENGLISH
) when creating DateTimeFormatter
to avoid ambiguity and ensure consistent parsing across different systems.Alternatively, if you prefer to use SimpleDateFormat
(though java.time
is generally preferred for its clarity and robustness):
<code class="language-java">SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");</code>
Remember to meticulously match the format patterns ("EEE MMM dd HH:mm:ss zzz yyyy" and "yyyy-MM-dd") to your input and desired output, paying close attention to the case of letters (as defined in the SimpleDateFormat
documentation). However, using java.time
is strongly encouraged for its improved error handling and clarity.
The above is the detailed content of How to Convert 'EEE MMM dd HH:mm:ss ZZZ yyyy' Dates to java.sql.Date for MySQL?. For more information, please follow other related articles on the PHP Chinese website!