我有以下代码。 java日期时间的字符串形式是gmt+0。因此,我稍后需要根据不同的本地时区对其进行转换,但是当我尝试设置默认时区时,它会继续返回 8 小时,因为我的计算机处于 gmt+8。输出向我显示 2017-12-09 09:00 :00 但我想保留为 2017-12-09 17:00:00 因为这是 gmt+0。
String existingTime = "2017-12-09 17:00:00";
String newTime = "2017-12-09 14:00:00";
Date existingDateTime = null;
Date newDateTime = null;
Date localexistingDateTime = null;
Date localnewDateTime = null;
DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
// sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:30"));
try {
existingDateTime = dateTimeFormat.parse(existingTime);
newDateTime = dateTimeFormat.parse(newTime);
System.out.println("GMT existingDateTime" + sdf.format(existingDateTime));
System.out.println("GMT newDateTime" + sdf.format(newDateTime));
} catch (ParseException ex) {
System.out.println("MyError:Parse Error has been caught for date parse close");
ex.printStackTrace(System.out);
}
最佳答案
此代码片段可能会帮助您开始使用 java.time
,现代 Java 日期和时间 API。在 Java Specification Request 之后,它也称为 JSR-310。首先描述了它。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String existingTime = "2017-12-09 17:00:00";
OffsetDateTime existingDateTime = LocalDateTime.parse(existingTime, formatter)
.atOffset(ZoneOffset.UTC);
System.out.println("UTC existingDateTime: " + existingDateTime.format(formatter));
System.out.println("Pyongyang existingDateTime: "
+ existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Pyongyang"))
.format(formatter));
System.out.println("Singapore existingDateTime: "
+ existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Singapore"))
.format(formatter));
运行代码片段的输出是:
UTC existingDateTime: 2017-12-09 17:00:00
Pyongyang existingDateTime: 2017-12-10 01:30:00
Singapore existingDateTime: 2017-12-10 01:00:00
这是我在计算机上得到的输出(在欧洲/柏林时区),但是让现代类独立于 JVM 时区更容易,因此您应该在计算机上得到相同的输出。
编辑:您在评论中询问是否无法使用 GMT+09:00 的偏移量来代替时区。我不确定你为什么要这样做,因为现实中的人生活在时区而不是偏移量中,但当你知道如何做时,这很容易:
System.out.println("GMT+09:00 existingDateTime: "
+ existingDateTime.withOffsetSameInstant(ZoneOffset.ofHours(9))
.format(formatter));
输出:
GMT+09:00 existingDateTime: 2017-12-10 02:00:00
一个LocalDateTime
是没有时区或偏移信息的日期和时间。由于您的字符串不包含偏移量或区域,因此我使用它进行解析。由于您告诉我您的日期时间是 GMT+0,所以我将其转换为 OffsetDateTime
首先要考虑UTC偏移量。从那里可以直接将其转换为不同的本地时区。因此,我演示了对于几个时区,每次使用我用于解析的相同格式化程序来格式化日期时间,因为我收集您倾向于喜欢 yyyy-MM-dd HH:mm:ss
格式。
我总是以地区/城市格式给出时区。这是明确的(与三个字母缩写相反;例如,PYT 可能表示巴拉圭时间或平壤时间)。如果时区使用夏令时 (DST),它会自动处理夏令时。甚至区域偏移的历史性变化也是内置的。
学习使用java.time
,参见Oracle Tutorial on Date Time并在 Stack Overflow 上搜索相关问题,始终寻找 java.time
答案(有大量使用过时类的旧答案,请跳过这些)。网络上的更多地方都拥有宝贵的资源。您的搜索引擎和区分好坏的能力是您的 friend 。
关于Java设置时区不默认为gmt+0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729293/