Skip to content

Commit

Permalink
Fix parsing dates with trailing spaces (Resolves #11) (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
angelosilvestre authored Jan 13, 2024
1 parent 71ec7e2 commit 8bbfb1e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
9 changes: 7 additions & 2 deletions lib/domain/dart_rss.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,21 @@ extension SafeParseDateTime on DateTime {
if (str == null) {
return null;
}

const dateFormatPatterns = [
'EEE, d MMM yyyy HH:mm:ss Z',
];

// DateTime.parse returns null if the input has
// trailing spaces. Remove the spaces to avoid that.
final trimmedDate = str.trim();
try {
return DateTime.parse(str);
return DateTime.parse(trimmedDate);
} catch (_) {
for (final pattern in dateFormatPatterns) {
try {
final format = DateFormat(pattern);
return format.parse(str);
return format.parse(trimmedDate);
} catch (_) {}
}
}
Expand Down
17 changes: 11 additions & 6 deletions test/safe_parse_date_time_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,32 @@ import 'package:dart_rss/dart_rss.dart';
import 'package:test/test.dart';

void main() {
group('about SafeParseDateTime, ', () {
test('it can parse ISO-8601', () {
group('SafeParseDateTime, ', () {
test('parses ISO-8601', () {
final date = SafeParseDateTime.safeParse('2018-04-06T13:02:47Z')!;

expect(date.year, 2018);
expect(date.month, 4);
expect(date.day, 6);
});

test('it can parse American-English-Format', () {
final date =
SafeParseDateTime.safeParse('Tue, 02 Jul 2019 16:47:24 +0000')!;
test('parses American-English-Format', () {
final date = SafeParseDateTime.safeParse('Tue, 02 Jul 2019 16:47:24 +0000')!;

expect(date.year, 2019);
expect(date.month, 7);
expect(date.day, 2);
});

test('incorrect date returns null', () {
test('returns null for incorrect dates', () {
final date = SafeParseDateTime.safeParse('Tue 12');
expect(date, null);
});

test('parses dates with trailing whitespaces', () {
final date = SafeParseDateTime.safeParse('2024-01-08T00:19:00Z ')!;

expect(date, DateTime.utc(2024, 1, 8, 0, 19, 0));
});
});
}

0 comments on commit 8bbfb1e

Please sign in to comment.