Support space-separated date/time format for DateTimeType (#4370)

Signed-off-by: Jimmy Tanagra <jcode@tanagra.id.au>
This commit is contained in:
jimtng 2024-09-07 06:44:20 +10:00 committed by GitHub
parent 72753be8cc
commit 1145613cba
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 1 deletions

View File

@ -22,6 +22,7 @@ import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.zone.ZoneRulesException;
import java.util.Locale;
import java.util.regex.Pattern;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -64,6 +65,9 @@ public class DateTimeType implements PrimitiveType, State, Command, Comparable<D
private static final DateTimeFormatter PARSER_TZ_RFC = DateTimeFormatter.ofPattern(DATE_PARSE_PATTERN_WITH_TZ_RFC);
private static final DateTimeFormatter PARSER_TZ_ISO = DateTimeFormatter.ofPattern(DATE_PARSE_PATTERN_WITH_TZ_ISO);
private static final Pattern DATE_PARSE_PATTERN_WITH_SPACE = Pattern
.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}.*");
// internal patterns for formatting
private static final String DATE_FORMAT_PATTERN_WITH_TZ_RFC = "yyyy-MM-dd'T'HH:mm[:ss[.SSSSSSSSS]]Z";
private static final DateTimeFormatter FORMATTER_TZ_RFC = DateTimeFormatter
@ -84,7 +88,11 @@ public class DateTimeType implements PrimitiveType, State, Command, Comparable<D
try {
// direct parsing (date and time)
try {
date = parse(zonedValue);
if (DATE_PARSE_PATTERN_WITH_SPACE.matcher(zonedValue).matches()) {
date = parse(zonedValue.substring(0, 10) + "T" + zonedValue.substring(11));
} else {
date = parse(zonedValue);
}
} catch (DateTimeParseException fullDtException) {
// time only
try {

View File

@ -36,6 +36,7 @@ import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
/**
* @author Thomas Eichstaedt-Engelen - Initial contribution
@ -260,6 +261,22 @@ public class DateTimeTypeTest {
assertTrue(dt1.compareTo(dt1) == 0);
}
// This can only test explicit time zones, as we cannot mock the system default time zone
@ParameterizedTest
@ValueSource(strings = { //
"2024-09-05T15:30:00Z", //
"2024-09-05 15:30Z", //
"2024-09-05 16:30+0100", //
"2024-09-05T17:30:00.000+0200", //
"2024-09-05T17:30:00.000+02:00" //
})
public void parserTest(String input) {
ZonedDateTime zdtReference = ZonedDateTime.parse("2024-09-05T15:30:00Z");
ZonedDateTime zdt = new DateTimeType(input).getZonedDateTime().withZoneSameInstant(zdtReference.getZone());
assertThat(zdt, is(zdtReference));
}
@Test
public void zonedParsingTest() {
DateTimeType dt1 = new DateTimeType("2019-06-12T17:30:00Z");