Home >Database >Mysql Tutorial >How to Convert 'EEE MMM dd HH:mm:ss ZZZ yyyy' to java.sql.Date for MySQL?
Convert "EEE MMM dd HH:mm:ss ZZZ yyyy" date format to java.sql.Date
Question:
You try to convert the date in "EEE MMM dd HH:mm:ss ZZZ yyyy" format to "YYYY-MM-DD" format for inserting into MySQL database, but the inserted date is incorrect and every row is the same.
Solution using Java 8:
<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>
Explanation:
This code leverages modern Java 8 time classes and uses the fluent API for clarity and simplicity. It parses the date string using ZonedDateTime
, converts it to LocalDate
, and then uses java.sql.Date.valueOf()
to create a LocalDate
object from java.sql.Date
.
Note:
SimpleDateFormat
pattern to match the desired format: <code class="language-java">SimpleDateFormat formatnow = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); SimpleDateFormat formatneeded = new SimpleDateFormat("yyyy-MM-dd");</code>
The above is the detailed content of How to Convert 'EEE MMM dd HH:mm:ss ZZZ yyyy' to java.sql.Date for MySQL?. For more information, please follow other related articles on the PHP Chinese website!