[microtik] Fix changed date format in firmware v7.10 (#15362)

Signed-off-by: lsiepel <leosiepel@gmail.com>
This commit is contained in:
lsiepel 2023-08-06 20:00:12 +02:00 committed by GitHub
parent faceef6fd4
commit 3b9b0236b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 3 deletions

View File

@ -14,6 +14,7 @@ package org.openhab.binding.mikrotik.internal.util;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.util.Locale;
import java.util.regex.Matcher;
@ -32,15 +33,26 @@ import org.eclipse.jdt.annotation.Nullable;
public class Converter {
private static final DateTimeFormatter ROUTEROS_FORMAT = DateTimeFormatter.ofPattern("MMM/dd/yyyy kk:mm:ss",
Locale.ENGLISH);
private static final DateTimeFormatter ROUTEROS_FORMAT_NEW = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss",
Locale.ENGLISH);
private static final Pattern PERIOD_PATTERN = Pattern.compile("(\\d+)([a-z]+){1,3}");
public @Nullable static LocalDateTime fromRouterosTime(@Nullable String dateTimeString) {
if (dateTimeString == null) {
if (dateTimeString == null || dateTimeString.length() < 19) {
return null;
}
try {
// As of Firmware 7.10 the date format has changed to "yyyy-MM-dd HH:mm:ss"
if (dateTimeString.length() == 19) {
return LocalDateTime.parse(dateTimeString, ROUTEROS_FORMAT_NEW);
} else {
String fixedTs = dateTimeString.substring(0, 1).toUpperCase() + dateTimeString.substring(1);
return LocalDateTime.parse(fixedTs, ROUTEROS_FORMAT);
}
} catch (DateTimeParseException e) {
return null;
}
String fixedTs = dateTimeString.substring(0, 1).toUpperCase() + dateTimeString.substring(1);
return LocalDateTime.parse(fixedTs, ROUTEROS_FORMAT);
}
public @Nullable static LocalDateTime routerosPeriodBack(@Nullable String durationString) {

View File

@ -36,6 +36,18 @@ public class ConverterTest {
is(equalTo(LocalDateTime.of(2021, 1, 7, 9, 14, 11, 0))));
assertThat(Converter.fromRouterosTime("feb/13/2021 23:59:59"),
is(equalTo(LocalDateTime.of(2021, 2, 13, 23, 59, 59, 0))));
assertThat(Converter.fromRouterosTime("2021-02-13 23:59:59"),
is(equalTo(LocalDateTime.of(2021, 2, 13, 23, 59, 59, 0))));
assertThat(Converter.fromRouterosTime("2020-12-11 20:45:40"),
is(equalTo(LocalDateTime.of(2020, 12, 11, 20, 45, 40, 0))));
assertThat(Converter.fromRouterosTime("2021-01-07 09:14:11"),
is(equalTo(LocalDateTime.of(2021, 1, 7, 9, 14, 11, 0))));
assertNull(Converter.fromRouterosTime(null));
assertNull(Converter.fromRouterosTime(""));
assertNull(Converter.fromRouterosTime("2021-18-07 09:14:11"));
assertNull(Converter.fromRouterosTime("feb/41/2021 23:59:59"));
}
@Test