Java ResultSet 如何在 UTC 中获取时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1469256/
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-12 12:38:24  来源:igfitidea点击:

Java ResultSet how to getTimeStamp in UTC

javajdbc

提问by kal

The database has data in UTC and when I try to get data

数据库中有 UTC 格式的数据,当我尝试获取数据时

java.util.Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME);
cal.setTime(ts);

Is there anything wrong with this?

这有什么问题吗?

采纳答案by akf

Your DateFormat instance is most likely displaying the value in local time. When displaying your value, give this a try:

您的 DateFormat 实例很可能以当地时间显示该值。当显示你的价值时,试试这个:

java.util.Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME);
cal.setTime(ts);

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(cal.getTime()));

EDIT: to your comment:

编辑:对您的评论:

What if I use GMT, would that be an issue in SimpleDateFormat

如果我使用 GMT,那会不会是 SimpleDateFormat 的问题

SimpleDateFormatcan use general timezones (GMT +/- n), RFC822, and text ("if they have names" as the JavaDoc states - see this postfor info on the names).

SimpleDateFormat可以使用通用时区 (GMT +/- n)、RFC822和文本(“如果它们有名称”,如 JavaDoc 所述 -有关名称的信息,请参阅此帖子)。

回答by Subu

java.util.Calendar cal = Calendar.getInstance(); 
cal.setTimeZone(TimeZone.getTimeZone("UTC")); 
java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME, cal); 

This should do the trick!

这应该可以解决问题!