我无法将日期变量传递给构造函数-无法解析

时间:2019-04-14 17:24:35

标签: java date jsp servlets

在用于向数据库表中添加新记录的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块之外看不到该变量。

1 个答案:

答案 0 :(得分:2)

您的let hour = currentDate.getHours(); // I changed the code below // let not0 = new Date(year, month, date, 9) // to this let not0 = new Date(year, month, hour > 9 ? date + 1 : date, 9); 构造函数需要一个Doctors参数,而不是一个LocalDate(这很好,因为Date的设计很差并且已经过时,而Date属于java.time,这是一种现代且更好用的Java日期和时间API)。

额外的好处是,在解析失败的情况下,解析LocalDate会引发 unchecked 而不是Checked异常,因此编译器不会介意。

额外的奖励LocalDate解析您的格式yyyy-MM-dd作为默认格式,即没有任何显式格式化程序。这是因为该格式符合标准ISO 8601。

LocalDate

链接