"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-09
Browse:313

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:

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3