Awale
Awale

Reputation: 1

Get LocalDate from the @RequestBody, convert it to dd/mm/yyyy format, convert it back to LocalDate and store it in the database

I am creating a Rest API applicaton which tracks users` expenses. I have date variable of type LocalDate and the default format is yyyy-mm-dd but I want to store dd/mm/yyyy in the database

what I tried was get the localDate from RequestBody, format it to dd/mm/yyyy (which returns string) and convert it back to LocalDate. However, date is still being stored default format, yyyy-mm-dd. I think the problem is in LocalDate.parse(dateString, formatter); because it converts back to the default format or ignores the new format. Not sure but this my assumption Here is my code:

@PostMapping()
    public ResponseEntity<Expense> addExpense(@RequestBody @Valid Expense expense) {
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.UK);

        LocalDate date = expense.getDate();

        String dateString = date.format(formatter);

        LocalDate formattedDate = LocalDate.parse(dateString, formatter);
        
        expense.setDate(formattedDate); 

I dont know if there a way to take input as dd/mm/yyyy format in the request instead of yyyy-mm-dd

Upvotes: -1

Views: 239

Answers (1)

Ahmed Mera
Ahmed Mera

Reputation: 583

The issue here is that the LocalDate object always uses the "yyyy-MM-dd" format for storage and parsing by default.

If you want to store the date in the "dd/MM/yyyy" format in your database, you need to convert the date to a string before storing it. However, typically, it's recommended to store dates in the standard "yyyy-MM-dd" format in the database for consistency and simplicity in handling date-related operations.

You can customize the deserialization of the LocalDate object in your request by using a custom deserializer.


public class CustomLocalDateDeserializer extends JsonDeserializer<LocalDate> {

    @Override
    public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {
        String date = jsonParser.getText();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        try {
            return LocalDate.parse(date, formatter);
        } catch (DateTimeParseException e) {
            throw new RuntimeException(e);
        }
    }
}

Here your DTO request:


public class Expense {
    
    @JsonDeserialize(using = CustomLocalDateDeserializer.class)
    private LocalDate date;

    // other fields, getters and setters
}

In this way you can get the localdate as you want.

Upvotes: 0

Related Questions