将日期转换为不同的时区 [英] Convert date to different timezone

查看:115
本文介绍了将日期转换为不同的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java日期和日历从一个时区到另一个时区的简单转换。我尝试运行以下代码

I am trying to obtain a simple conversion from one time zone into another using Java Date and Calendar. I am trying to run the following code

    Calendar instance = Calendar.getInstance(TimeZone.getTimeZone("Europe/London"));
    Date date = instance.getTime();
    System.out.println(date);

    GregorianCalendar instance2 = new GregorianCalendar(TimeZone.getTimeZone("Europe/Athens"));
    instance2.setTime(instance.getTime());
    System.out.println(instance2.getTime());

但仍然返回相同的日期,而不是+1小时...整个问题似乎微不足道但我找不到任何简单的答案。感谢您的帮助。

but that still returns the same date, rather than +1 hour... The whole problem seems trivial but i cannot find any simple answer to this. Thanks in advance for your help.

推荐答案

当使用 System.out.println日期);或System.out.println(instance2.getTime()); , Date TimeZone独立,并且始终以当地时区打印日期。

When you print the date using System.out.println(date); or System.out.println(instance2.getTime());, the Date returned by instance2.getTime() is TimeZone independent and always prints the date in local timezone.

想要使用 DateFormat / SimpleDateFormat

  DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z");
  formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));
  System.out.println(formatter.format(date));

  formatter.setTimeZone(TimeZone.getTimeZone("Europe/Athens"));
  System.out.println(formatter.format(instance2.getTime()))

这篇关于将日期转换为不同的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆