在我的Spring Boot应用程序中,我必须不使用JODA将ISO 8601日期时间转换为localdatetime。目前我正在做的是
String receivedDateTime = "2019-11-13T00:11:08+05:00";
ZonedDateTime zonedDateTime = ZonedDateTime.parse(receivedDateTime);
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date();
try {
date = utcFormat.parse(zonedDateTime.toString());
} catch (ParseException e) {
e.printStackTrace();
}
当我将带有+00:00的receiveDateTime用作“ 2019-11-13T00:11:08 + 00:00”时,它不会给出任何解析错误,但不会进行任何转换。当我最后使用+01:00时,它还会给出解析错误。
更新:1
根据@Deadpool答案,我使用它的方式是
String receivedDateTime = "2019-11-13T00:11:08+05:00";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart().appendOffset("+HH:MM","+00:00").optionalEnd()
.optionalStart().appendOffset("+HHMM","0000").optionalEnd()
.toFormatter();
OffsetDateTime dt = OffsetDateTime.parse(receivedDateTime,formatter);
LocalDateTime ldt = dt.toLocalDateTime();
System.out.println(ldt);
,它打印的 ldt 的值为 2019-11-13T00:11:08 。
更新2: 我尝试使用同一示例的C#,它给了我这个日期时间 {2019-11-12 11:11:08 AM} ,它看起来正确,因为输入时间是格林尼治标准时间+5小时,而本地时间是美国东部时间。因此,当它转换后,它可以追溯到11月12日。这是代码
var timeString = "2019-11-13T00:11:08+05:00";
DateTime d2 = DateTime.Parse(timeString,null,System.Globalization.DateTimeStyles.RoundtripKind);
Console.WriteLine("Hello World!" + d2);
更新3:归结为以下解决方案输入字符串“ 2019-11-13T06:01:41 + 00:00”,输出为本地日期“ 2019-11-13T00:01” :41“,系统默认的ZoneId为” America / Chicago“,即格林尼治标准时间-06:00
private LocalDateTime convertUtcStringToLocalDateTime(String UtcDateTime) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart().appendOffset("+HH:MM","0000").optionalEnd()
.toFormatter();
OffsetDateTime dateTime = OffsetDateTime.parse(UtcDateTime,formatter);
return dateTime.atZonesameInstant(ZoneId.of(ZoneId.systemDefault().getId())).toLocalDateTime();
}