Fabio Plaka
Fabio Plaka

Reputation: 148

Convert String to LocalDateTime

I have an error in registration of tasks because the time must be converted from String to LocalDateTime and I don't know how to convert.

Below is my Task class:

@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 Task() {
    }

    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 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;
    }
}

In TaskController class I have that function to register Tasks in the database:

@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";
}

And in TaskService is the function for adding tasks in TaskController:

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


Please can someone resolve this error:

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]

and this:

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]

I have spent many days and I cannot resolve this.

Thanks in advance!

Upvotes: 2

Views: 6231

Answers (2)

Rentius2407
Rentius2407

Reputation: 1148

You can write a converter to convert from a String to LocalDateTime and vice versa.

@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));
    }
}

If you want to define a converter for each variable use

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

Upvotes: 2

theNoobProgrammer
theNoobProgrammer

Reputation: 97

Use below to convert the time from String to LocalDateTime, but make sure you are getting the time in String form.

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

Upvotes: 1

Related Questions