V
V
vitya_brodov2021-09-03 14:03:48
Java
vitya_brodov, 2021-09-03 14:03:48

How to correctly set a pattern for a date in java?

I have LocalDateTime, which is set in the format: 2021-08-18T00:48:02.4089693
How can it only accept in the pattern: year/month/day hour/minutes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-09-03
@vitya_brodov

Well, let's say I understood something (I'm an expert)) ...
You can set the date format in Jason in this way:
1. We write our own converter.

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.databind.util.Converter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static org.apache.http.util.TextUtils.isBlank;

public class CustomStringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(String value) {
        if (isBlank(value)) return null;
        var formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;  // Вот тут задается формат даты
        return LocalDateTime.parse(value, formatter);
    }

    @Override
    public JavaType getInputType(TypeFactory typeFactory) {
        return typeFactory.constructType(String.class);
    }

    @Override
    public JavaType getOutputType(TypeFactory typeFactory) {
        return typeFactory.constructType(LocalDateTime.class);
    }
}

2. Add an annotation over the required field:
class WithDate {
    @JsonDeserialize(converter = CustomStringToLocalDateTimeConverter.class)
    private LocalDateTime startTime;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question