将 UTC 时间转换为 Java 中的本地时区

converting a UTC time to a local time zone in Java(将 UTC 时间转换为 Java 中的本地时区)
本文介绍了将 UTC 时间转换为 Java 中的本地时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道这个主题已经被打死了,但是在搜索了几个小时之后我不得不问这个问题.

I know this subject has been beaten to death but after searching for a few hours to this problem I had to ask.

我的问题:根据客户端应用程序 (iphone) 的当前时区计算服务器上的日期.客户端应用程序以秒为单位告诉服务器其时区距 GMT 有多远.然后我想使用这些信息来计算服务器中的日期.服务器上的日期都存储为 UTC 时间.所以我想在转换为本地时区后获取 UTC Date 对象的 HOUR.

My Problem: do calculations on dates on a server based on the current time zone of a client app (iphone). The client app tells the server, in seconds, how far away its time zone is away from GMT. I would like to then use this information to do computation on dates in the server. The dates on the server are all stored as UTC time. So I would like to get the HOUR of a UTC Date object after it has been converted to this local time zone.

我目前的尝试:

int hours = (int) Math.floor(secondsFromGMT / (60.0 * 60.0));
int mins = (int) Math.floor((secondsFromGMT - (hours * 60.0 * 60.0)) / 60.0);
String sign = hours > 0 ? "+" : "-";

Calendar now = Calendar.getInstance();
TimeZone t = TimeZone.getTimeZone("GMT" + sign + hours + ":" + mins);
now.setTimeZone(t);

now.setTime(someDateTimeObject);

int hourOfDay = now.get(Calendar.HOUR_OF_DAY);

变量 hour 和 mins 表示本地时区与 GMT 相差的小时和分钟.调试此代码后 - 变量小时、分钟和符号是正确的.

The variables hour and mins represent the hour and mins the local time zone is away from GMT. After debugging this code - the variables hour, mins and sign are correct.

问题是 hourOfDay 没有返回正确的小时 - 它返回的是 UTC 时间的小时,而不是本地时间.想法?

The problem is hourOfDay does not return the correct hour - it is returning the hour as of UTC time and not local time. Ideas?

推荐答案

您的时区字符串格式不正确.试试这个,

You timezone string is formulated incorrectly. Try this,

String sign = secondsFromGMT > 0 ? "+" : "-";
secondsFromGMT = Math.abs(secondsFromGMT);      
int hours = secondsFromGMT/3600;
int mins = (secondsFromGMT%3600)/60;
String zone = String.format("GMT%s%02d:%02d", sign, hours, mins);          
TimeZone t = TimeZone.getTimeZone(zone);

这篇关于将 UTC 时间转换为 Java 中的本地时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
java get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)