Home > Database > Mysql Tutorial > How to Convert a Java Epoch Timestamp to a MySQL Timestamp String?

How to Convert a Java Epoch Timestamp to a MySQL Timestamp String?

DDD
Release: 2024-12-14 22:42:22
Original
218 people have browsed it

How to Convert a Java Epoch Timestamp to a MySQL Timestamp String?

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template