本文介绍了Calendar.getInstance(TimeZone.getTimeZone(" UTC"))未返回UTC时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑我得到的结果 Calendar.getInstance(TimeZone.getTimeZone(UTC))方法调用,它返回IST时间。

I am really confused with the result I am getting with Calendar.getInstance(TimeZone.getTimeZone("UTC")) method call, it's returning IST time.

以下是我使用的代码

Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

我收到的回复是:

Sat Jan 25 15:44:18 IST 2014

所以我尝试将默认TimeZone更改为UTC,然后我检查,然后它工作正常

So I tried changing the default TimeZone to UTC and then I checked, then it is working fine

Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

TimeZone tz  = TimeZone.getDefault() ;
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());
TimeZone.setDefault(tz);

结果:

Sat Jan 25 16:09:11 IST 2014
Sat Jan 25 10:39:11 UTC 2014

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

System.out。 println(cal_Two.getTime())调用从 getTime()返回 Date 。它是 Date ,它被转换为 println 的字符串,并且该转换将使用默认的 IST 你的情况下的时区。

The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.

你需要明确地使用 DateFormat.setTimeZone()在所需的时区打印日期

You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.

编辑:由@Laurynas提供,考虑这个:

Courtesy of @Laurynas, consider this:

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
       new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

这篇关于Calendar.getInstance(TimeZone.getTimeZone(" UTC"))未返回UTC时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:53