RED-9322 & RED-9036: backport
This commit is contained in:
parent
566472bfb0
commit
04632787f1
@ -11,12 +11,15 @@ import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.format.ResolverStyle;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.experimental.FieldDefaults;
|
||||
@ -30,6 +33,7 @@ public class DateConverter {
|
||||
|
||||
private static DateTimeFormatter DATE_TIME_FORMATTER;
|
||||
private static final List<Locale> LOCALES = Arrays.asList(Locale.UK, Locale.US);
|
||||
private static int BASE_YEAR = 1950; // base year 1950 means, that "yy" will be interpreted in range 1950-2049
|
||||
|
||||
|
||||
public Optional<Date> parseDate(String dateAsString) {
|
||||
@ -96,7 +100,11 @@ public class DateConverter {
|
||||
while ((line = reader.readLine()) != null) {
|
||||
String pattern = line.trim();
|
||||
if (!pattern.isEmpty()) {
|
||||
builder.appendOptional(DateTimeFormatter.ofPattern(pattern, Locale.UK));
|
||||
if (hasTwoDigitsForYear(pattern)) {
|
||||
builder.appendOptional(setBaseYear(pattern));
|
||||
} else {
|
||||
builder.appendOptional(DateTimeFormatter.ofPattern(pattern, Locale.UK));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
@ -106,6 +114,32 @@ public class DateConverter {
|
||||
}
|
||||
|
||||
|
||||
private boolean hasTwoDigitsForYear(String input) {
|
||||
// Regex to match any string with exactly two 'y' characters
|
||||
Pattern pattern = Pattern.compile("^[^y]*(y[^y]*){2}$");
|
||||
Matcher matcher = pattern.matcher(input);
|
||||
|
||||
return matcher.matches();
|
||||
|
||||
}
|
||||
|
||||
|
||||
private DateTimeFormatter setBaseYear(String pattern) {
|
||||
|
||||
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
|
||||
if (pattern.startsWith("yy")) {
|
||||
String editedPattern = pattern.substring(2);
|
||||
builder.appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, BASE_YEAR).appendPattern(editedPattern).toFormatter();
|
||||
} else if (pattern.endsWith("yy")) {
|
||||
String editedPattern = pattern.substring(0, pattern.length() - 2);
|
||||
builder.appendPattern(editedPattern).appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2, BASE_YEAR).toFormatter();
|
||||
} else {
|
||||
throw new RuntimeException("Date format not supported: " + pattern);
|
||||
}
|
||||
return builder.toFormatter();
|
||||
}
|
||||
|
||||
|
||||
private String removeTrailingDot(String dateAsString) {
|
||||
|
||||
String str = dateAsString;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user