Home >Database >Mysql Tutorial >How to Convert 'EEE MMM dd HH:mm:ss ZZZ yyyy' to java.sql.Date for MySQL?

How to Convert 'EEE MMM dd HH:mm:ss ZZZ yyyy' to java.sql.Date for MySQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-12 08:04:46616browse

How to Convert

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:

  • Always specify a locale for formatters to ensure consistent parsing across different locales.
  • If possible, use long time zone IDs or offsets rather than ambiguous three-letter time zone abbreviations.
  • If Java 8 classes are not available, modify the 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn