Home > Database > Mysql Tutorial > Why Does SimpleDateFormat.parse Produce Unexpected Output When Converting UNIX Timestamps?

Why Does SimpleDateFormat.parse Produce Unexpected Output When Converting UNIX Timestamps?

Barbara Streisand
Release: 2024-10-27 16:26:29
Original
845 people have browsed it

Why Does SimpleDateFormat.parse Produce Unexpected Output When Converting UNIX Timestamps?

Different Output Formats from SimpleDateFormatter.parse

In a Java program, the SimpleDateFormat class is utilized to convert dates into specified formats. However, it has been observed that in some cases, parsing a date using SimpleDateFormatter.parse can result in a different format than the one specified during formatting.

This issue arises when converting UNIX timestamps into date strings. Here's a simplified example:

<code class="java">String ep ="a1527069600";
Long epoch = Long.parseLong(ep.substring(1, ep.length()));
Date dt = new Date(epoch*1000L);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));

System.out.println("SDF.Format - "+sdf.format(dt));
System.out.println("SDF.parse - "+sdf.parse(sdf.format(dt)));</code>
Copy after login

In this example, while the format specified for sdf is "dd/MM/yyyy hh:mm:ss a", the output of sdf.parse is in a different format, "Wed May 23 15:30:00 IST 2018."

Solution

To resolve this issue, avoid passing date strings to a MySQL database. Instead, use date objects. Java provides the java.time API for modern date and time handling. For your specific scenario, you can use a LocalDateTime object:

<code class="java">    String ep ="a1527069600";
    long epoch = Long.parseLong(ep.substring(1));
    Instant inst = Instant.ofEpochSecond(epoch);
    LocalDateTime ldt = inst.atZone(ZoneId.of("Asia/Calcutta")).toLocalDateTime();

    PreparedStatement ps = myDatabaseConnection.prepareStatement(
            "insert into my_table (my_date_time) values (?)");
    ps.setObject(1, ldt);</code>
Copy after login

This approach ensures consistent date formatting and eliminates the parsing issue encountered with SimpleDateFormatter.parse.

The above is the detailed content of Why Does SimpleDateFormat.parse Produce Unexpected Output When Converting UNIX Timestamps?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template