Java Calendar.getInstance(TimeZone.getTimeZone("UTC")) 没有返回 UTC 时间

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

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

java

提问by vicky

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

我真的对我通过Calendar.getInstance(TimeZone.getTimeZone("UTC"))方法调用得到的结果感到困惑,它正在返回 IST 时间。

Here is the code I used

这是我使用的代码

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

and the response I got is:

我得到的回应是:

Sat Jan 25 15:44:18 IST 2014

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

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

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);

Result:

结果:

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

Am I missing something here?

我在这里错过了什么吗?

采纳答案by mockinterface

The System.out.println(cal_Two.getTime())invocation returns a Datefrom getTime(). It is the Datewhich is getting converted to a string for println, and that conversion will use the default ISTtimezone in your case.

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

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

您需要明确使用DateFormat.setTimeZone()Date在所需时区打印。

EDIT: Courtesy of @Laurynas, consider this:

编辑:由@Laurynas 提供,请考虑:

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());

回答by poitroae

Try to use GMTinstead of UTC. They refer to the same time zone, yet the name GMTis more common and might work.

尝试使用GMT而不是UTC. 它们指的是同一个时区,但名称GMT更常见并且可能有用。

回答by PopoFibo

java.util.Dateis independent of the timezone. When you print cal_Twothough the Calendarinstance has got its timezone set to UTC, cal_Two.getTime()would return a Dateinstance which does not have a timezone (and is always in the default timezone)

java.util.Date与时区无关。当您打印时,cal_Two尽管Calendar实例的时区设置为UTCcal_Two.getTime()将返回一个Date没有时区的实例(并且始终处于默认时区)

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

Output:

输出:

 Sat Jan 25 16:40:28 IST 2014
    sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null] 

From the javadoc of TimeZone.setDefault()

来自 javadoc TimeZone.setDefault()

Sets the TimeZone that is returned by the getDefault method. If zone is null, reset the default to the value it had originally when the VM first started.

设置由 getDefault 方法返回的 TimeZone。如果 zone 为空,则将默认值重置为 VM 首次启动时的初始值。

Hence, moving your setDefault()before cal_Twois instantiated you would get the correct result.

因此,setDefault()cal_Two实例化之前移动您将获得正确的结果。

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

Calendar cal_Three = Calendar.getInstance();
System.out.println(cal_Three.getTime());

Output:

输出:

Sat Jan 25 11:15:29 UTC 2014
Sat Jan 25 11:15:29 UTC 2014

回答by Fabian

Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()

is working for me

正在为我工​​作

回答by Khalid Habib

    Following code is the simple example to change the timezone
    Following code is the simple example to change the timezone
public static void main(String[] args) {
          //get time zone
          TimeZone timeZone1 = TimeZone.getTimeZone("Asia/Colombo");
          Calendar calendar = new GregorianCalendar();
          //setting required timeZone
          calendar.setTimeZone(timeZone1);
          System.out.println("Time :" + calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND));

       }

if you want see the list of timezones, here is the follwing code

如果您想查看时区列表,请查看以下代码

public static void main(String[] args) {

    String[] ids = TimeZone.getAvailableIDs();
    for (String id : ids) {
        System.out.println(displayTimeZone(TimeZone.getTimeZone(id)));
    }

    System.out.println("\nTotal TimeZone ID " + ids.length);

}

private static String displayTimeZone(TimeZone tz) {

    long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
    long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset())
                              - TimeUnit.HOURS.toMinutes(hours);
    // avoid -4:-30 issue
    minutes = Math.abs(minutes);

    String result = "";
    if (hours > 0) {
        result = String.format("(GMT+%d:%02d) %s", hours, minutes, tz.getID());
    } else {
        result = String.format("(GMT%d:%02d) %s", hours, minutes, tz.getID());
    }

    return result;

}

回答by Monika V

You are definitely missing a small thing and that is you are not setting a default value:

你肯定错过了一件小事,那就是你没有设置默认值:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

So the code would look like:

所以代码看起来像:

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

Explanation: If you want to change the time zone, set the default time zone using TimeZone.setDefault()

说明:如果要更改时区,请使用设置默认时区TimeZone.setDefault()