Converting Epoch to MySQL Timestamp in Java
In Java, you can use the java.time API to handle date and time operations effectively. The System.currentTimeMillis() method returns the current time since the epoch in milliseconds. To convert it to a MySQL timestamp, you can follow these steps:
1. Utilize java.time.Instant:
Instant timestamp = Instant.ofEpochSecond(epochNow);
2. Convert Instant to OffsetDateTime (optional):
If you want to represent the timestamp with time zone information, you can use OffsetDateTime:
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(timestamp, ZoneId.systemDefault());
3. Format to MySQL timestamp string:
You can use the DateTimeFormatter to format OffsetDateTime to a MySQL timestamp string:
String mySQLtimestamp = offsetDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss"));
This will produce a MySQL timestamp string in the format "2013-09-23:50:00".
Note: The legacy java.sql.Timestamp class can also be used for handling MySQL timestamps, but it is recommended to use the java.time API for improved functionality and accuracy.
The above is the detailed content of How to Convert a Java Epoch Timestamp to a MySQL Timestamp String?. For more information, please follow other related articles on the PHP Chinese website!