首页 > 解决方案 > 在 Java 中解析 LocalDate 到日期的问题

问题描述

我正在尝试在我的 Java 代码中解析 LocalDate 的日期,但我不断收到以下错误:

{代码:“unknown.unexpected”,详细信息:“无法在索引 0 处解析文本 '02/28/1936'”,元:null}

我的代码如下:

private Date dateOfBirth;
public SearchByDateCommand(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth != null ? Date.valueOf(dateOfBirth) : null;
}

我在这里做错了什么?

标签: javadateparsinglocaldate

解决方案


用这个:

private Date dateOfBirth;
public SearchByDateCommand(LocalDate dateOfBirth) {
    this.dateOfBirth = dateOfBirth != null ? Date.from(dateOfBirth.atStartOfDay(ZoneId.systemDefault()).toInstant()) : null;
}

您必须向 LocalDate 添加时间,解释时区内的日期和时间,获取自纪元以来的秒数/毫秒数,最后,创建一个 java.util.Date。


推荐阅读