MySQL 时间戳到 Java 日期的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3473421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:05:29  来源:igfitidea点击:

MySQL timestamp to Java date conversion

javamysqljdbc

提问by JJunior

How can I convert time in unix timestamp to normal time?

如何将unix时间戳中的时间转换为正常时间?

采纳答案by BalusC

Your question is vague and ambiguous. I'll leave the timezone ambiguity away.

你的问题含糊不清。我将离开时区歧义。

How can I convert time in unix timestamp to normal time?

如何将unix时间戳中的时间转换为正常时间?

I suspect that you're somehow obtaining a longor maybe a Stringvalue from the DB instead of a Date. In JDBC, you would normally like to use the appropriate methods to obtain the DB-specific datatypes. The MySQL TIMESTAMPdatatype can be obtained by ResultSet#getTimestamp()which gives you a java.sql.Timestampwhich in turn is a subclass of java.util.Date.

我怀疑您以某种方式从数据库中获取了一个long或一个String值,而不是Date. 在 JDBC 中,您通常希望使用适当的方法来获取特定于 DB 的数据类型。MySQLTIMESTAMP数据类型可以通过ResultSet#getTimestamp()which 给你 a获得,而java.sql.Timestamp后者又是java.util.Date.

In a nut, the following should do:

简而言之,应该执行以下操作:

Date date = resultSet.getTimestamp("columnname");

To format it further in a human readable format whenever you're going to present it to the enduser, use SimpleDateFormat. Click the link, it contains an overview of all patterns. Here's an example:

要在将其呈现给最终用户时将其进一步格式化为人类可读的格式,请使用SimpleDateFormat. 单击链接,它包含所有模式的概述。下面是一个例子:

String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

To do all the other way round, use respectively SimpleDateFormat#parse()and PreparedStatement#setTimestamp().

反过来,请分别使用SimpleDateFormat#parse()PreparedStatement#setTimestamp()

回答by Thilo

Unix timestamp is seconds since "epoch". Java's currentTimeMillis are milliseconds since "epoch". You can get a Java Date object with a simple multiplication like this:

Unix 时间戳是自“纪元”以来的秒数。Java 的 currentTimeMillis 是自“纪元”以来的毫秒数。你可以通过一个简单的乘法得到一个 Java Date 对象,如下所示:

 Date dateFromUnixTime = new Date( 1000l * unixTime) ;

From there, you can format it using the normal date formatting tools in Java.

从那里,您可以使用 Java 中的普通日期格式化工具对其进行格式化。