如何让 Java 解析和格式化具有相同时区的日期/时间?我一直在获取本地时区 [英] How do I get Java to parse and format a date/time with the same time zone? I keep getting the local timezone

查看:18
本文介绍了如何让 Java 解析和格式化具有相同时区的日期/时间?我一直在获取本地时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序将所有 Java 日期保留为 UTC.解析它们很容易,但是当我将它们打印出来时,显示屏会显示计算机的本地时区,我想将其显示为 UTC.

My application keeps all Java Date's in UTC. Parsing them is easy, but when I print them out, the display shows the computer's local time zone, and I want to show it as UTC.

示例代码:

String sample = "271210 200157 UTC";
SimpleDateFormat dfmt = new SimpleDateFormat("ddMMyy HHmmss Z");
Date result = dfmt.parse(sample);
System.out.printf("%tc\n", result);

结果是

美国东部标准时间 2010 年 12 月 27 日星期一 15:01:57

Mon Dec 27 15:01:57 EST 2010

我想要的是

2010 年 12 月 27 日星期一 20:01:57 UTC

Mon Dec 27 20:01:57 UTC 2010

显然我必须设置一些 Locale 和 TimeZone 值,但我不知道将它们放在哪里.谢谢拍

Clearly I have to set some Locale and TimeZone values, but I don't see where to put them. Thanks Pat

推荐答案

您可以为 DateFormat 设置时区:

  dfmt.setTimeZone(timeZone);

此外,您不想打印 Date 对象本身,而是再次使用 DateFormat

Also, you do not want to print the Date object itself, but again use the DateFormat

  String formattedDate = dfmt.format(result);

这篇关于如何让 Java 解析和格式化具有相同时区的日期/时间?我一直在获取本地时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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