Home >Database >Mysql Tutorial >Why does SimpleDateFormat.parse output differently than specified when converting UNIX timestamps to dates?

Why does SimpleDateFormat.parse output differently than specified when converting UNIX timestamps to dates?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 03:06:28508browse

Why does SimpleDateFormat.parse output differently than specified when converting UNIX timestamps to dates?

SimpleDateFormatter.parse Outputs Differently Than Specified

When converting UNIX timestamps to dates using SimpleDateFormat, you may encounter discrepancies between the specified format and the output.

In the given example, the goal is to convert a UNIX timestamp ("a1527069600") to a date in the "dd/MM/yyyy hh:mm:ss a" format. However, using SimpleDateFormatter.format followed by SimpleDateFormatter.parse yields a different output.

Cause of Discrepancy

The discrepancy occurs because SimpleDateFormatter.parse expects a string in the exact format specified during instantiation ("dd/MM/yyyy hh:mm:ss a"). In this case, SimpleDateFormatter.format outputs the date in a format different from the expected input format, causing the parse operation to fail.

Solution

To avoid this issue, it's recommended to not pass date strings to MySQL databases. Instead, use date objects. The modern Java date and time API, java.time, provides classes like LocalDateTime that make date handling easier.

Example:

<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();

System.out.println(ldt.toString()); // Output: 2018-05-23T15:30

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

This code converts the UNIX timestamp to a LocalDateTime, which can be directly inserted into the MySQL database.

Conclusion:

By utilizing java.time and passing date objects instead of strings to MySQL, you can eliminate formatting issues and ensure the accuracy of date conversion.

The above is the detailed content of Why does SimpleDateFormat.parse output differently than specified when converting UNIX timestamps to dates?. 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