【问题标题】:After DateTimeZone.convertLocalToUTC timezone still shows local之后 DateTimeZone.convertLocalToUTC 时区仍显示本地
【发布时间】:2013-10-24 06:57:55
【问题描述】:

我使用 DateTimeZone.convertLocalToUTC 将本地时间转换为 UTC。时间已正确更改,但转换后,时区信息仍显示原始本地时区。请参考下面的示例代码

Date gmttime = new Date(tz.convertLocalToUTC(System.currentTimeMillis(),false));
System.out.println(gmttime.toString());

输出: 2013 年 10 月 16 日星期三 12:58:19 IST

请注意粗体值,我预计它是 UTC 。如果我遗漏了什么,请告诉我。

【问题讨论】:

  • 仅供参考,new Date 已被贬低
  • 那么如果 new Date() 被贬低了还有什么选择呢?
  • 我的意思是 new Date(....) 被贬低了。查看我发布的答案

标签: java time timezone jodatime timestamp-with-timezone


【解决方案1】:

#Date.toString() 将以当地时区打印日期。

使用SimpleDateFormat 打印为特定TimeZone 格式化的Date

public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat format = new SimpleDateFormat("E MMM  dd HH:mm:ss:SS z");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(format.format(date));
}

【讨论】:

  • 时间 (HH:MM:SS) 在 UTC 中正确显示,只有 TimeZone 打印为 Local
【解决方案2】:

试试:

final Date date = new Date();
final String ISO_FORMAT = "E MMM dd HH:mm:ss zzz yyyy";
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
final TimeZone utc = TimeZone.getTimeZone("UTC");
sdf.setTimeZone(utc);
System.out.println(sdf.format(date));

输出:

Wed Oct 16 08:53:50 UTC 2013

【讨论】:

    【解决方案3】:

    convertLocalToUTC 将本地时刻转换为具有相同本地时间的标准 UTC 时刻。 http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      相关资源
      最近更新 更多