Skip to content

Commit

Permalink
!109 DateHelper 支持多种自定义格式解析日期字符串
Browse files Browse the repository at this point in the history
* DateHelper 支持多种自定义格式解析日期字符串
  • Loading branch information
codering authored and entropy-cloud committed Jan 22, 2025
1 parent 0fec237 commit 1a7df8e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
15 changes: 14 additions & 1 deletion nop-commons/src/main/java/io/nop/commons/util/DateHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
// }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -81,4 +82,14 @@ public void testToString() {
System.out.println(str);
assertEquals(str, DateHelper.formatDateTime(dateTime, "yyyy-MM-dd HH:mm:ss"));
}
}

@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));
}
}

0 comments on commit 1a7df8e

Please sign in to comment.