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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-12 07:12:45980browse

How to Convert

Convert "EEE MMM dd HH:mm:ss ZZZ yyyy" format to java.sql.Date

This article describes how to convert a timestamp in the "EEE MMM dd HH:mm:ss ZZZ yyyy" format into the "YYYY-MM-DD" format acceptable to the MySQL database. Here’s how:

  1. Parse: Use the SimpleDateFormat class to parse the input timestamp. Ensure format strings and locales are precisely defined to avoid ambiguity.
  2. Formatting: Use the second SimpleDateFormat to convert the parsed date into the desired "YYYY-MM-DD" format.
  3. Conversion: To store a date into the database, create a java.sql.Date object from the formatted date.

Optimization plan

A more concise and efficient way is to use the modern 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 uses the ZonedDateTime and LocalDate classes to parse and convert timestamps.

Suggestion:

  • To avoid locale effects, specify Locale.ROOT.
  • Avoid using ambiguous three-letter time zone abbreviations, specify the full time zone ID or UTC offset.
  • Verify that the latest MySQL JDBC driver supports direct insertion of LocalDate objects without conversion.

The above is the detailed content of How to Convert 'EEE MMM dd HH:mm:ss ZZZ yyyy' to a MySQL-Compatible java.sql.Date?. 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