4

我需要将毫秒转换为 GMT 日期(在 Android 应用程序中),例如:

1372916493000

当我通过这段代码转换它时:

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(millis);
Date date = cal.getTime();

结果是07:41 07/04/2013。当我只使用时,结果是一样的:

Date date = new Date(millis);

不幸的是,结果看起来不正确,它看起来像我的当地时间。我尝试通过此服务转换相同的数字,结果是05:41 07/04/2013,我认为这是正确的。所以我有两个小时的差异。有人有任何建议/提示我的转换有什么问题吗?

4

5 回答 5

14

如果结果看起来不正确System.out.println(date),那就不足为奇了,因为Date.toString将日期转换为本地时区的字符串表示形式。要查看 GMT 的结果,您可以使用它

SimpleDateFormat df = new SimpleDateFormat("hh:ss MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = df.format(millis);
于 2013-07-04T15:00:40.473 回答
2

在转换过程中,您似乎弄乱了您的本地时区和 UTC 时区。

假设您在伦敦(目前伦敦比格林威治标准时间早 1 小时),毫秒是您所在时区(在本例中为伦敦)的时间。

然后,您可能应该:

Calendar cal = Calendar.getInstance();
// Via this, you're setting the timezone for the time you're planning to do the conversion
cal.setTimeZone(TimeZone.getTimeZone("Europe/London"));
cal.setTimeInMillis(1372916493000L);
// The date is in your home timezone (London, in this case)
Date date = cal.getTime();


TimeZone destTz = TimeZone.getTimeZone("GMT");
// Best practice is to set Locale in case of messing up the date display
SimpleDateFormat destFormat = new SimpleDateFormat("HH:mm MM/dd/yyyy", Locale.US);
destFormat.setTimeZone(destTz);
// Then we do the conversion to convert the date you provided in milliseconds to the GMT timezone
String convertResult = destFormat.parse(date);

请让我知道我是否正确理解了您的观点?

干杯

于 2013-07-04T14:57:26.633 回答
2
于 2018-01-30T23:09:25.430 回答
1

试试这个

public class Test{
    public static void main(String[] args) throws IOException {
        Test test=new Test();
        Date fromDate = Calendar.getInstance().getTime();
        System.out.println("UTC Time - "+fromDate);
        System.out.println("GMT Time - "+test.cvtToGmt(fromDate));
    }
    private  Date cvtToGmt( Date date )
        {
           TimeZone tz = TimeZone.getDefault();
           Date ret = new Date( date.getTime() - tz.getRawOffset() );

           // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
           if ( tz.inDaylightTime( ret ))
           {
              Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

              // check to make sure we have not crossed back into standard time
              // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
              if ( tz.inDaylightTime( dstDate ))
              {
                 ret = dstDate;
              }
           }

           return ret;
        }
}

测试结果
UTC 时间 - 2012 年
5 月 15 日星期二 16:24:14 IST GMT 时间 - 2012 年 5 月 15 日星期二 10:54:14 IST

于 2013-07-04T14:47:04.027 回答
0

Date date = cal.getTime();

返回日期通过创建

public final Date getTime() {
    return new Date(getTimeInMillis());
}

wheregetTimeInMillis()返回没有任何 TimeZone 的毫秒数。

我建议在这里寻找如何做你想做的事情how-to-handle-calendar-timezones-using-java

于 2013-07-04T14:51:56.997 回答