MySQL时间戳到Java日期的转换 [英] MySQL timestamp to Java date conversion
问题描述
如何将Unix时间戳中的时间转换为正常时间?
How can I convert time in unix timestamp to normal time?
推荐答案
您的问题模棱两可.我将消除时区的歧义.
Your question is vague and ambiguous. I'll leave the timezone ambiguity away.
如何将unix时间戳中的时间转换为正常时间?
我怀疑您是从数据库而不是Date
处获取long
或String
值.在JDBC中,通常希望使用适当的方法来获取特定于DB的数据类型.可以通过 java.sql.Timestamp
反过来又是 java.util.Date
.
I suspect that you're somehow obtaining a long
or maybe a String
value 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 TIMESTAMP
datatype can be obtained by ResultSet#getTimestamp()
which gives you a java.sql.Timestamp
which in turn is a subclass of 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:
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
要进行其他所有操作,请分别使用 PreparedStatement#setTimestamp()
.
To do all the other way round, use respectively SimpleDateFormat#parse()
and PreparedStatement#setTimestamp()
.
这篇关于MySQL时间戳到Java日期的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!