Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix parsing dates with trailing spaces (Resolves #11) #39

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
});
});
}