[英]How to best determine whether the date format is MM/dd or DD/mm in java
我有文件列表,我需要使用 java 分析它們。 日期字段作為String
從文件中讀取,我需要將其解析為LocalDatTime
。 問題是現在知道日期的第一部分是月還是日。
其中的格式可以是任何格式,但最有可能采用以下格式。
"yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm","MM/dd/yyyy HH:mm", "yyyy-MM-dd HH:mm",
"MM/dd/yy HH:mm"
例如
9/8/2020 23:50
9/8/2020 23:55
9/9/2020 00:00
在上述情況下,日期字段可以從日期更改為9/8/2020 23:50
9/9/2020 00:00
時開始猜測。 這意味着日期從 8 日更改為 9 日,因此格式為MM/dd/yyyy HH:mm
9/8/2020 23:00
9/8/2020 23:50
10/8/2020 00:00
在上述情況下,日期字段可以從日期從9/8/2020 23:55
10/9/2020 00:00
更改時開始猜測。 這意味着日期從 9 日更改為 10 日,因此格式為dd/MM/yyyy HH:mm
該文件也可以是2020-09-08 23:00:00
。 我唯一知道的是,系列中的日期會改變,而月份很少會改變。
解決這個問題的最佳方法是什么。
解決方案之一可能只是計算第一部分和第二部分的變化並比較結果。 這不是特別有效,但很簡單:
// true - day/month/year
// false - month/day
public static boolean isDayMonthYearFormat(List<String> sortedDates) {
int firstPartChangeAmount = 0;
int secondPartChangeAmount = 0;
int prvOne = -1;
int prvTwo = -1;
boolean count = false;
for (String date : sortedDates) {
String[] parts = date.split("[\\/\\s+:]");
int one = Integer.parseInt(parts[0]);
int two = Integer.parseInt(parts[1]);
if (count) {
firstPartChangeAmount += prvOne < one ? 1 : 0;
secondPartChangeAmount += prvTwo < two ? 1 : 0;
}
count = true;
prvOne = one;
prvTwo = two;
}
if (firstPartChangeAmount == secondPartChangeAmount)
throw new RuntimeException("can't detect between MM/dd and DD/mm");
return firstPartChangeAmount > secondPartChangeAmount;
}
輸出:
System.out.println(isDayMonthYearFormat(Arrays.asList("9/8/2020 23:50", "9/8/2020 23:55", "9/9/2020 00:00"))); // false
System.out.println(isDayMonthYearFormat(Arrays.asList("9/8/2020 23:00", "9/8/2020 23:50", "10/8/2020 00:00"))); // true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.