diff --git a/nop-commons/src/main/java/io/nop/commons/util/DateHelper.java b/nop-commons/src/main/java/io/nop/commons/util/DateHelper.java index b57958a70..31e4d3bdf 100644 --- a/nop-commons/src/main/java/io/nop/commons/util/DateHelper.java +++ b/nop-commons/src/main/java/io/nop/commons/util/DateHelper.java @@ -287,6 +287,19 @@ public static LocalDate parseDate(String s, String pattern) { return LocalDate.parse(s, formatter); } + public static LocalDate safeParseDate(String s, String ...patterns) { + if (StringHelper.isEmpty(s)) + return null; + for(String pattern : patterns) { + try { + DateTimeFormatter formatter = buildFormatter(pattern); + return LocalDate.parse(s, formatter); + } catch (Exception ignore) { + } + } + return null; + } + public static LocalDateTime parseDateTime(String s, String pattern) { if (StringHelper.isEmpty(s)) return null; @@ -419,4 +432,4 @@ public static boolean isMonthDay(@Name("date") LocalDate date, @Name("monthDay") // return ConvertHelper.stringToLong(s) * factor; // return (long) (ConvertHelper.stringToDouble(s) * factor); // } -} \ No newline at end of file +} diff --git a/nop-commons/src/test/java/io/nop/commons/util/TestDateHelper.java b/nop-commons/src/test/java/io/nop/commons/util/TestDateHelper.java index 5c2c5086e..69b41da85 100644 --- a/nop-commons/src/test/java/io/nop/commons/util/TestDateHelper.java +++ b/nop-commons/src/test/java/io/nop/commons/util/TestDateHelper.java @@ -17,6 +17,7 @@ import java.util.TimeZone; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class TestDateHelper { @@ -81,4 +82,14 @@ public void testToString() { System.out.println(str); assertEquals(str, DateHelper.formatDateTime(dateTime, "yyyy-MM-dd HH:mm:ss")); } -} \ No newline at end of file + + @Test + public void testSafeParseDate() { + String[] patterns = new String[]{"yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd", "yyMMdd"}; + assertEquals(DateHelper.parseDate("2024-01-02"), DateHelper.safeParseDate("20240102", patterns)); + assertEquals(DateHelper.parseDate("2024-01-02"), DateHelper.safeParseDate("2024-01-02", patterns)); + assertEquals(DateHelper.parseDate("2024-01-02"), DateHelper.safeParseDate("2024/01/02", patterns)); + assertEquals(DateHelper.parseDate("2024-01-02"), DateHelper.safeParseDate("240102", patterns)); + assertNull(DateHelper.safeParseDate("2024_01_02", patterns)); + } +}