Home >Java >javaTutorial >How to Convert an Epoch Timestamp to a MySQL Timestamp in Java?
Converting Epoch to MySQL Timestamp in Java
Question:
How can I convert a given epoch timestamp to the MySQL timestamp format?
Code:
long epochNow = System.currentTimeMillis()/1000; long epochWeek = 604800; long date7daysAgo = epochNo2013 w - epochWeek; String mySQLtimestamp = /* 2013-09-23:50:00 */
Answer:
Using java.time:
Java SE 8 introduced java.time, a modern and enhanced Date-Time API. Here's how you can convert epoch to MySQL timestamp using java.time:
import java.time.LocalDateTime; long epochTimestamp = /* your epoch timestamp here */; LocalDateTime timestamp = LocalDateTime.ofEpochSecond(epochTimestamp, 0, ZoneOffset.UTC); String mySQLtimestamp = timestamp.toString(); // 2013-09-23 23:54:11
The LocalDateTime type represents a date-time with an optional time zone. By default, it uses the UTC time zone, which ensures consistency with MySQL timestamps.
Note:
The MySQL timestamp format in your code ("2013-09-23:50:00") includes the time component only. If you require the full date-time representation in your code, it should be updated to match the format of mySQLtimestamp obtained using toString().
The above is the detailed content of How to Convert an Epoch Timestamp to a MySQL Timestamp in Java?. For more information, please follow other related articles on the PHP Chinese website!