如何从模式创建Java时间瞬间? [英] How to create Java time instant from pattern?
问题描述
考虑一个代码:
TemporalAccessor date = DateTimeFormatter.ofPattern("yyyy-MM-dd").parse("9999-12-31");
Instant.from(date);
最后一行抛出异常:
Unable to obtain Instant from TemporalAccessor: {},ISO resolved to 9999-12-31 of type java.time.format.Parsed
如何从yyyy-MM-dd
模式创建Instant
?
推荐答案
字符串"9999-12-31"仅包含有关日期的信息.它不包含有关时间或偏移量的任何信息.因此,没有足够的信息来创建Instant
. (其他日期和时间库更为宽松,但java.time
避免默认使用这些值)
The string "9999-12-31" only contains information about a date. It does not contain any information about the time-of-day or offset. As such, there is insufficient information to create an Instant
. (Other date and time libraries are more lenient, but java.time
avoids defaulting these values)
您的首选是使用LocalDate
而不是`Instant:
Your first choice is to use a LocalDate
instead of an `Instant:
LocalDate date = LocalDate.parse("9999-12-31");
您的第二个选择是对日期进行后期处理,以将其转换为需要时区(此处选择为巴黎)的瞬间:
Your second choice is to post process the date to convert it to an instant, which requires a time-zone, here chosen to be Paris:
LocalDate date = LocalDate.parse("9999-12-31");
Instant instant = date.atStartOfDay(ZoneId.of("Europe/Paris")).toInstant();
您的第三个选择是将时区添加到格式化程序中,并默认为日期时间:
Your third choice is to add the time-zone to the formatter, and default the time-of-day:
static final DateTimeFormatter FMT = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd")
.parseDefaulting(ChronoField.NANO_OF_DAY, 0)
.toFormatter()
.withZone(ZoneId.of("Europe/Paris"));
Instant instant = FMT.parse("9999-31-12", Instant::from);
(如果这不起作用,请确保您具有最新的JDK 8版本,因为该区域中的错误已得到修复.)
(If this doesn't work, ensure you have the latest JDK 8 release as a bug was fixed in this area).
值得注意的是,这些可能性都不直接使用TemporalAccessor
,因为该类型是低级框架接口,不是大多数应用程序开发人员都可以使用的接口.
It is worth noting that none of these possibilities use TemporalAccessor
directly, because that type is a low-level framework interface, not one for most application developers to use.
这篇关于如何从模式创建Java时间瞬间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!