Answer the question
In order to leave comments, you need to log in
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
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);
}
}
class WithDate {
@JsonDeserialize(converter = CustomStringToLocalDateTimeConverter.class)
private LocalDateTime startTime;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question