我有SimpleDateFormat构造函数
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
Run Code Online (Sandbox Code Playgroud)
我正在解析字符串 "2013-09-29T18:46:19Z".
我读过这里Z表示GMT/UTC时区.但是当我在控制台上打印这个日期时,它会为返回的日期打印IST timezne.
现在我的问题是我的输出是对还是错?
我正在将日期/日期时间字符串转换为OffsetDateTime并且我有日期时间格式,它可能具有这些值之一
yyyy-MM-dd, yyyy/MM/dd
Run Code Online (Sandbox Code Playgroud)
有时有或没有时间,我需要将其转换为OffsetDateTime.
我试过下面的代码
// for format yyyy-MM-dd
DateTimeFormatter DATE_FORMAT = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
.toFormatter();
Run Code Online (Sandbox Code Playgroud)
由于没有时间,我将其设置为默认值,但是当我尝试解析时
OffsetDateTime.parse("2016-06-06", DATE_FORMAT)
Run Code Online (Sandbox Code Playgroud)
它抛出错误就像
线程“main”中的异常 java.time.format.DateTimeParseException:无法解析文本“2016-06-06”:无法从 TemporalAccessor 获取 OffsetDateTime:{},ISO 解析为 java 类型的 2016-06-06T00:00 .time.format.Parsed 已解析
谁能帮我解决这个问题吗?
我想将字符串转换为 OffsetDateTime 数据类型。字符串具有以下形状:
2017-11-27T19:06:03
Run Code Online (Sandbox Code Playgroud)
我尝试了两种方法:
方法一
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter formatter = new java.time.format.DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
return OffsetDateTime.parse(timestamp, formatter);
}
Run Code Online (Sandbox Code Playgroud)
方法二:
public static OffsetDateTime convertString(String timestamp) {
java.time.format.DateTimeFormatter parser = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
java.time.LocalDateTime dt = java.time.LocalDateTime.parse(timestamp, parser);
ZonedDateTime zdt = ZonedDateTime.of(dt, java.time.ZoneId.of("UTC"));
return OffsetDateTime.from(zdt);
}
Run Code Online (Sandbox Code Playgroud)
第一种方法不起作用,因为它抱怨以下内容:
java.time.format.DateTimeParseException:无法解析文本“2017-11-27T19:02:42”:无法从 TemporalAccessor 获取 OffsetDateTime:{},ISO 解析为 java 类型的 2017-11-27T19:02:42 .time.format.Parsed
据我所知,它来自字符串没有 ZoneId 的事实。如何在格式化程序上覆盖 ZoneId 以忽略它?
第二种方法来自这个问题并且有效,但它需要 2 个额外的转换,我想避免这些额外的转换。
任何帮助将不胜感激。