Translating Epoch to MySQL Timestamp in Java
Java programmers often encounter the need to convert Epoch time, representing the number of seconds since the Unix epoch, into MySQL timestamp format. Here's how to achieve this conversion using Java's modern Date-Time API, java.time.
java.time
Introduced with Java SE 8, java.time provides a comprehensive and error-resistant Date-Time API. It maps ANSI SQL types to java.time types, as shown below:
ANSI SQL | Java SE 8 |
---|---|
DATE | LocalDate |
TIME | LocalTime |
TIMESTAMP | LocalDateTime |
TIME WITH TIMEZONE | OffsetTime |
TIMESTAMP WITH TIMEZONE | OffsetDateTime |
Converting Epoch to MySQL Timestamp
Using java.time, one can easily convert Epoch time to a MySQL timestamp:
// Get current epoch time in milliseconds long epochNow = System.currentTimeMillis(); // Create a LocalDateTime object from the epoch time LocalDateTime timestampNow = Instant.ofEpochMilli(epochNow).atZone(ZoneId.systemDefault()).toLocalDateTime(); // Convert to MySQL timestamp format using DateTimeFormatter String mySQLtimestamp = timestampNow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss"));
Example Usage
In your provided code snippet, you have epochNow representing the current time and date7daysAgo representing a timestamp 7 days in the past. You can easily convert both timestamps to MySQL format using the above code and store them in mySQLtimestamp.
String mySQLtimestampNow = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochNow), ZoneId.systemDefault()) .format(DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss")); String mySQLtimestamp7DaysAgo = LocalDateTime.ofInstant(Instant.ofEpochMilli(date7daysAgo), ZoneId.systemDefault()) .format(DateTimeFormatter.ofPattern("yyyy-MM-dd:HH:mm:ss"));
The above is the detailed content of How to Convert Epoch Time to MySQL Timestamp in Java?. For more information, please follow other related articles on the PHP Chinese website!