0

I save the column gioBatDau in MySQL as datetime, in POJO as

@Column(name = "GioBatDau")
@Temporal(TemporalType.TIMESTAMP)  
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") 
private Date gioBatDau;

I can't add data to the database:

<form:input type="text" class="form-control" id="gioBatDau" 
   placeholder="Giờ bắt đầu" name="gioBatDau" path="gioBatDau"/>
10
  • Additionally, what is the error you are receiving? Copy and pasting your input does not help very much. It would help to see the controller as well.
    – cela
    Commented Sep 4, 2023 at 20:18
  • What is the meaning of your gioBatDau field? Does that represent a moment, a specific point on the time line? Or does that represent a date and a time-of-day without the context of a time zone or offset-from-UTC? (Tip: Translating all your text to English is helpful when posting here on the English edition of Stack Overflow.) Commented Sep 4, 2023 at 23:39
  • 1
    In that case you are probably best off using LocalDateTime in Java and datetime in MySQL (Java Date is ill suited).
    – Anonymous
    Commented Sep 5, 2023 at 10:32
  • 1
    I tried switching to LocalDateTime and it said @Temporal should only be set on a java.util.Date or java.util.Calendar property: com.ndh.pojo.Suatchieu.gioBatDau Commented Sep 5, 2023 at 10:45
  • 1
    I tried removing the @Temporal line but it still doesn't work Commented Sep 5, 2023 at 10:59

1 Answer 1

2

Based on your new comments, you may need a custom converter for swapping between Strings and LocalDateTime.

Here is the converter:

import org.springframework.core.convert.converter.Converter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public final class LocalDateTimeConverter implements Converter<String, LocalDateTime> {

    private final DateTimeFormatter formatter;

    public LocalDateTimeConverter(String dateFormat) {
        this.formatter = DateTimeFormatter.ofPattern(dateFormat);
    }

    @Override
    public LocalDateTime convert(String source) {
        if (source == null || source.isEmpty()) {
            return null;
        }

        try {
            return LocalDateTime.parse(source, formatter);
        } catch (DateTimeParseException e) {
            // Log the error here
            // return null if you need the 400 error, or set a default date
            return null; 
        }
    }
}

You will need to register the converter. I am assuming you are not using Spring Boot, so you can register it in WebMvcConfigurerAdapter like so:

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
class WebMvcContext extends WebMvcConfigurerAdapter {
 
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new LocalDateTimeConverter("yyyy-MM-dd'T'HH:mm:ss"));
    }
}

Column definition will look like this:

@Column(name = "GioBatDau")
private LocalDateTime gioBatDau;

Previous Answer and still relevant

One option to resolve the issue you're facing is to switch the column type from java.util.Date to java.time.LocalDateTime and then specify the correct date-time format.

Here is the snippet:

import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Column;
import java.time.LocalDateTime;

public class YourEntity {

    @Column(name = "GioBatDau")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    private LocalDateTime gioBatDau;

}

Why Use java.time.LocalDateTime?

Since Java 8, it's recommended to use java.time.LocalDateTime or java.time.LocalDate over java.util.Date for several reasons:

  1. Immutability: Classes in java.time package are immutable, making them thread-safe.

  2. Rich API: They provide a richer API for date-time manipulation.

  3. Clearer Semantics: These classes have clearer semantics for dealing with dates, times, and time-zones.

  4. Time Zone Handling: Easier to work with time-zones.

Controller/Service-level Conversion

While it's convenient to use @DateTimeFormat at the entity level, it's often considered better practice to keep entity classes as clean as possible. You can perform the conversion at the service or controller level. This makes your entity classes more reusable and decouples them from the web layer of your application.

For more information on the java.time package, you can read the official Java documentation .

3
  • 1
    Given the use of TemporalType.TIMESTAMP, and the fact that "Giờ bắt đầu" apparently translates to "start time", I suspect that despite their choice of formatting pattern, the OP does not actually mean to use a date and time alone without a time zone or offset. I suspect Instant/OffsetDateTime along with a database column of SQL standard type TIMESTAMP WITH TIME ZONE is needed here. Commented Sep 4, 2023 at 23:37
  • I used LocalDateTime but it still doesn't work Commented Sep 5, 2023 at 10:58
  • @NguyenDucHung Could you show an example row or the DDL for the corresponding table?
    – cela
    Commented Sep 5, 2023 at 14:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.