且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法使用 Java 8 中的 DateTimeFormatter 和 ZonedDateTime 从 TemporalAccessor 获取 ZonedDateTime

更新时间:2022-06-20 18:35:20

这不起作用,因为您的输入(和您的格式化程序)没有时区信息.一个简单的方法是首先将您的日期解析为 LocalDate(没有时间或时区信息),然后创建一个 ZonedDateTime:

This does not work because your input (and your Formatter) do not have time zone information. A simple way is to parse your date as a LocalDate first (without time or time zone information) then create a ZonedDateTime:

public static ZonedDateTime convertirAFecha(String fecha) {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
  LocalDate date = LocalDate.parse(fecha, formatter);

  ZonedDateTime resultado = date.atStartOfDay(ZoneId.systemDefault());
  return resultado;
}