Skip to content

Commit

Permalink
improved date parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
deckerst committed Sep 12, 2022
1 parent 7bf464d commit 5d70ccb
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
24 changes: 22 additions & 2 deletions lib/utils/time_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ DateTime? dateTimeFromMillis(int? millis, {bool isUtc = false}) {
final _unixStampMillisPattern = RegExp(r'\d{13}');
final _unixStampSecPattern = RegExp(r'\d{10}');
final _dateYMD8Hms6Sub3Pattern = RegExp(r'(\d{8})([_-\s](\d{6})([_-\s](\d{3}))?)?');
final _dateY4M2D2H2m2s2Sub3Pattern = RegExp(r'(\d{4})-(\d{1,2})-(\d{1,2})-(\d{1,2})-(\d{1,2})-(\d{1,2})-(\d{1,3})');
final _dateY4M2D2H2m2s2Sub3Pattern = RegExp(r'(\d{4})-(\d{1,2})-(\d{1,2})[ -](\d{1,2})[.-](\d{1,2})[.-](\d{1,2})[.-](\d{1,3})?');
final _dateY4M2D2Hms6Pattern = RegExp(r'(\d{4})-(\d{1,2})-(\d{1,2}) (\d{6})');

DateTime? parseUnknownDateFormat(String? s) {
if (s == null) return null;
Expand Down Expand Up @@ -110,12 +111,31 @@ DateTime? parseUnknownDateFormat(String? s) {
final hour = int.tryParse(match.group(4)!);
final minute = int.tryParse(match.group(5)!);
final second = int.tryParse(match.group(6)!);
final millis = int.tryParse(match.group(7)!);
final millis = match.groupCount >= 7 ? int.tryParse(match.group(7) ?? '0') : 0;

if (year != null && month != null && day != null && hour != null && minute != null && second != null && millis != null) {
return DateTime(year, month, day, hour, minute, second, millis);
}
}

match = _dateY4M2D2Hms6Pattern.firstMatch(s);
if (match != null) {
final year = int.tryParse(match.group(1)!);
final month = int.tryParse(match.group(2)!);
final day = int.tryParse(match.group(3)!);
final timeString = match.group(4);

var hour = 0, minute = 0, second = 0;
if (timeString != null) {
hour = int.tryParse(timeString.substring(0, 2)) ?? 0;
minute = int.tryParse(timeString.substring(2, 4)) ?? 0;
second = int.tryParse(timeString.substring(4, 6)) ?? 0;
}

if (year != null && month != null && day != null) {
return DateTime(year, month, day, hour, minute, second);
}
}

return null;
}
2 changes: 2 additions & 0 deletions test/utils/time_utils_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,7 @@ void main() {
expect(parseUnknownDateFormat('Screenshot_20211028-115056_Aves'), DateTime(2021, 10, 28, 11, 50, 56, 0));

expect(parseUnknownDateFormat('Screenshot_2022-05-14-15-40-29-164_uri'), DateTime(2022, 5, 14, 15, 40, 29, 164));
expect(parseUnknownDateFormat('2019-02-18 16.00.12-DCM'), DateTime(2019, 2, 18, 16, 0, 12, 0));
expect(parseUnknownDateFormat('2019-10-31 135703'), DateTime(2019, 10, 31, 13, 57, 3, 0));
});
}

0 comments on commit 5d70ccb

Please sign in to comment.