我必须在UTC中存储UTC dateTime.
我已将特定时区中给出的dateTime转换为UTC.因为我遵循以下代码.
我的输入日期时间是"20121225 10:00:00 Z"时区是"亚洲/加尔各答"
我的服务器/数据库(oracle)在同一时区(IST)"亚洲/加尔各答"运行
获取此特定时区中的Date对象
String date = "20121225 10:00:00 Z";
String timeZoneId = "Asia/Calcutta";
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
DateFormat dateFormatLocal = new SimpleDateFormat("yyyyMMdd HH:mm:ss z");
//This date object is given time and given timezone
java.util.Date parsedDate = dateFormatLocal.parse(date + " "
+ timeZone.getDisplayName(false, TimeZone.SHORT));
if (timeZone.inDaylightTime(parsedDate)) {
// We need to re-parse because we don't know if the date
// is DST until it is parsed...
parsedDate = dateFormatLocal.parse(date + " "
+ timeZone.getDisplayName(true, TimeZone.SHORT));
} …Run Code Online (Sandbox Code Playgroud) Java8Instant.now()给出的当前时间已经采用 UTC 格式。我在CompileJava.net上创建了一个简单的沙箱测试来验证我的预期结果:
Timestamp createdDateUtc = Timestamp.from(Instant.now());
System.out.println(createdDateUtc);
LocalDateTime databaseUtcLocal = createdDateUtc.toLocalDateTime();
ZonedDateTime databaseUtcZoned = databaseUtcLocal.atZone(ZoneId.of("UTC"));
ZonedDateTime userTimezoneTime = databaseUtcZoned.withZoneSameInstant(ZoneId.of("Asia/Qatar"));
System.out.println(userTimezoneTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a")));
Run Code Online (Sandbox Code Playgroud)
注意:当前时间为 2018 年 12 月 1 日上午 11:16 UTC。
当我在在线编译器上运行此代码时,我得到输出:
2018-12-01 11:17:43.637
12/01/2018 02:17:43 PM
Run Code Online (Sandbox Code Playgroud)
但是当我在本地 JBOSS 服务器上运行此代码时,我得到以下输出:
2018-12-01 03:18:07.464
12/01/2018 06:18:07 AM
Run Code Online (Sandbox Code Playgroud)
这里可能出了什么问题?我的服务器 UTC 时钟是否不正确?我的本地服务器的物理位置位于加利福尼亚州。虽然这并不重要,但当我尝试使用Instant.now()太平洋时间来显示 UTC 时间时,这似乎很奇怪。
非常感谢任何帮助!
更新
正如已接受的答案所指出的,问题是我的Timestamp.from()方法:
System.out.println(Instant.now());
System.out.println(Timestamp.from(Instant.now()));
Run Code Online (Sandbox Code Playgroud)
输出:
2018-12-01T11:48:33.153Z
2018-12-01 03:48:33.171
Run Code Online (Sandbox Code Playgroud)
所以现在我的问题发生了变化。如果你有类似的问题,我在这里找到了 Stack Overflow 上的答案。我没有Timestamp.from(Instant.now())使用这个丑陋的混乱:
Timestamp.valueOf(ZonedDateTime.of(LocalDateTime.now(), ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime())
Run Code Online (Sandbox Code Playgroud)