将String转换为LocalDateTime

loading...


3

您好我在任务注册时出错,因为时间必须从 String 转换为 LocalDateTime ,我不知道如何转换 . 下面我展示了 Task 课程 .

@Entity
@Table(name = "task", schema = "public")
public class Task{

 @Id
 @GeneratedValue
 private Long id;

 @NotEmpty
 private String date;

 @NotEmpty
 private LocalDateTime startTime;

 @NotEmpty
 private LocalDateTime stopTime;

 @NotEmpty
 @Column(length=1000)
 private String description;

 @ManyToOne
 @JoinColumn(name="USER_EMAIL")
 private User user;

 public Long getId() {
     return id;
 }
 public void setId(Long id) {
    this.id = id;
 }
 public String getDate() {
     return date;
 }
 public void setDate(String date) {
    this.date = date;
 }
 public LocalDateTime getStartTime() {
    return startTime;
 }
 public void setStartTime(LocalDateTime startTime) {
    this.startTime = startTime;
 }
 public LocalDateTime getStopTime() {
    return stopTime;
 }
 public void setStopTime(LocalDateTime stopTime) {
    this.stopTime = stopTime;
 }
 public String getDescription() {
    return description;
 }
 public void setDescription(String description) {
     this.description = description;
 }
 public User getUser() {
    return user;
 }
 public void setUser(User user) {
    this.user = user;
 }

 public Task(String date, LocalDateTime startTime, LocalDateTime stopTime, String description, User user) {
    this.date = date;
    this.startTime = startTime;
    this.stopTime = stopTime;
    this.description = description;
    this.user = user;
 }
 public Task(String date, LocalDateTime startTime, LocalDateTime stopTime, String description) {
    this.date = date;
    this.startTime = startTime;
    this.stopTime = stopTime;
    this.description = description;
 }
 public Task() {
 }

}

TaskController 类中,我有这个函数来在db中注册任务

@PostMapping("/addTask")
public String addTask(@Valid Task task,
                      BindingResult bindingResult,
                      HttpSession session,
                      @RequestParam("datetime")
                          @DateTimeFormat(pattern = "dd.MM.yyyy HH:mm:ss.SSSZ") LocalDateTime dateAndTime) {

    if(bindingResult.hasErrors()){
        return "views/taskForm";
    }
    String email = (String) session.getAttribute("email");
    taskService.addTask(task, userService.findOne(email));
    return "redirect:/users";
}

并且 TaskService 是在 TaskController 中添加任务的功能 .

public void addTask(Task task, User user) {
    task.setUser(user);
    taskRepository.save(task);
}

Plase可以有人解决此错误

Failed to convert property value of type java.lang.String to required type java.time.LocalDateTime for property startTime; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.hibernate.validator.constraints.NotEmpty java.time.LocalDateTime] for value 09:00; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [09:00]

Failed to convert property value of type java.lang.String to required type java.time.LocalDateTime for property stopTime; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.hibernate.validator.constraints.NotEmpty java.time.LocalDateTime] for value 18:00; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [18:00]

因为我有很多天我无法解决 .

提前致谢!

loading...

2回答

  • 2

    使用下面的方法将时间从String转换为LocalDateTime,但请确保以String形式获取时间 .

    String str = "2018-12-10 12:30";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
    

  • 1

    您可以编写转换器以将 String 转换为 LocalDateTime ,反之亦然 .

    @Converter(autoApply = true)
    public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, String> {
    
        private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
        @Override
        public String convertToDatabaseColumn(LocalDateTime locDate) {
            return (locDate == null ? null : formatter.format(locDate));
        }
    
        @Override
        public LocalDateTime convertToEntityAttribute(String dateValue) {
            return (dateValue == null ? null : LocalDateTime.parse(dateValue, formatter));
        }
    }
    

    如果要为每个变量使用定义转换器

    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime stopTime;
    
评论

暂时没有评论!