java - 我无法将日期变量传递给构造函数 - 无法解析
问题描述
在用于向数据库表添加新记录的 servlet 中,我需要将 Date 值传递给构造函数,但是如果我在构造函数参数中解析,则会收到以下错误
“未处理的异常:java.text.ParseException”
当我在将值放入构造函数之前尝试使用 try catch 进行解析时,该值被视为未初始化。
这是实体类
@Entity
@Table(name = "doctors")
@Data
public class Doctors implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Id")
private Integer id;
@Column(name = "Name")
private String name;
@Column(name = "Surname")
private String surname;
@Column(name = "Title")
private String title;
@Column(name = "LicenseNumber")
private String licenseNumber;
@Column(name = "Phone")
private String phone;
@Column(name = "Email")
private String email;
@Column(name = "Nationality")
private String nationality;
@Column(name = "Speciality")
private String speciality;
@Column(name = "DateofBirth")
private LocalDate dateOfBirth;
@Column(name = "IsaTeacher")
private Boolean isATeacher;
public Doctors() {
}
public Doctors(Integer id, String name, String surname, String title, String licenseNumber, String phone, String email, String nationality, String speciality, LocalDate dateOfBirth, Boolean isATeacher) {
this.id = id;
this.name = name;
this.surname = surname;
this.title = title;
this.licenseNumber = licenseNumber;
this.phone = phone;
this.email = email;
this.nationality = nationality;
this.speciality = speciality;
this.dateOfBirth = dateOfBirth;
this.isATeacher = isATeacher;
}
}
这是我从 http 请求中得到的值
String dateOfBirth = req.getParameter("dateOfBirth");
这些是我让它发挥作用的尝试。这个给出“未处理的异常:java.text.ParseException”
Doctors doctor = new Doctors(name, surname, title, licenseNumber, phone, email, nationality, speciality, new SimpleDateFormat("yyyy-MM-dd").parse(dateOfBirth), Boolean.valueOf(isATeacher));
而这个“变量未初始化”
DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1;
try {
date1 = simpleDateFormat.parse(dateOfBirth);
} catch (ParseException e) {
e.printStackTrace();
}
Doctors doctor = new Doctors(name, surname, title, licenseNumber, phone, email, nationality, speciality, date1, Boolean.valueOf(isATeacher));
我真的不知道该怎么办。我必须处理异常才能解析 String 到日期,但是在 try 块之外看不到变量。
解决方案
您的Doctors
构造函数需要一个LocalDate
参数,而不是 a Date
(这很好,因为它属于 java.time,它是现代且更好的 Java 日期和时间 API,Date
设计不佳且早已过时)。LocalDate
额外的好处是,在解析失败的情况下,解析 aLocalDate
会引发未经检查的异常,而不是经过检查的异常,因此编译器不介意。
额外的额外奖励,LocalDate
将您的格式 yyyy-MM-dd 解析为默认值,即没有任何显式格式化程序。这是因为该格式符合 ISO 8601 标准。
Doctors doctor = new Doctors(name, surname, title, licenseNumber, phone,
email, nationality, speciality, LocalDate.parse(dateOfBirth),
Boolean.valueOf(isATeacher));
链接
- Oracle 教程:日期时间解释如何使用 java.time。
- 维基百科文章:ISO 8601
推荐阅读
- java - 在 DatePicker 中禁用日期而不启用以前禁用的日期
- react-native - react-native-image-picker 持久存储指向所选图像的链接
- node.js - 使用 nodejs 发送 formData POST 请求
- r - 来自每日数据的每周和每月财务数据
- python - 在 for 循环中合并不同列的 daframe
- javascript - flatlist 的数组过滤器,未定义 filterdFaqs
- ios - 如何偏移地图中心
- reactjs - React 中的会话超时与模态
- ios - ios中的Flutter firebase推送通知
- amazon-web-services - context.succeed(event) 的替代方案