Home > Java > javaTutorial > How to Convert Epoch Time to MySQL Timestamp in Java?

How to Convert Epoch Time to MySQL Timestamp in Java?

Mary-Kate Olsen
Release: 2024-12-11 13:44:16
Original
265 people have browsed it

How to Convert Epoch Time to MySQL Timestamp in Java?

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"));
Copy after login

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"));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template