gpt4 book ai didi

Java:日历实例的时间错误?

转载 作者:行者123 更新时间:2023-12-02 10:31:49 26 4
gpt4 key购买 nike

运行:

public class test {
@Test
public void displayDate() {
SimpleDateFormat MONTH_FORMAT = new SimpleDateFormat("MMM", Locale.getDefault());
String testDateStr = "2017-07-01T07:58:23.000Z";
Calendar calendar = getFormatedDate(testDateStr);
int yearInt = calendar.get(Calendar.YEAR);
String monthStr = MONTH_FORMAT.format(calendar.getTime()).toUpperCase();
int monthInt = calendar.get(Calendar.MONTH);
int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
int hour24 = calendar.get(Calendar.HOUR_OF_DAY);
int min = calendar.get(Calendar.MINUTE);
int sec = calendar.get(Calendar.SECOND);
System.out.println(testDateStr);
System.out.println(String.format("%s-%s-%s %s:%s:%s", yearInt, monthStr, dayInt, hour24, min, sec));
System.out.println(String.format("%s-%s-%s %s:%s:%s", yearInt, monthInt, dayInt, hour24, min, sec));

}

private Calendar getFormatedDate(String dateStr) {
Instant instant;
try {
instant = Instant.parse(dateStr);
} catch (DateTimeParseException e) {
e.printStackTrace();
return null;
}
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
Calendar calendar = GregorianCalendar.from(zdt);
return calendar;
}
}

我得到:

2017-07-01T07:58:23.000Z
2017-JUL-1 9:58:23
2017-6-1 9:58:23

请注意,我得到的小时 = 9,而预期为 7

问题

  1. 为什么会出现这样的结果
  2. 如何获得正确的结果?

谢谢!

最佳答案

Why this result

由于这一行:ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
您将您的时区强制设置为dateStr中定义的时区,因此日历将使用您的时区而不是原始时区。

How to get the right result ?

将您的 getFormatedDate 方法更改为:

private Calendar getFormatedDate(final String dateStr) {
final ZonedDateTime zdt = ZonedDateTime.parse(dateStr);
return GregorianCalendar.from(zdt);
}

关于Java:日历实例的时间错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53578964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com