diff --git a/lib/domain/dart_rss.dart b/lib/domain/dart_rss.dart index 34b43d2..744c9f0 100644 --- a/lib/domain/dart_rss.dart +++ b/lib/domain/dart_rss.dart @@ -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 (_) {} } } diff --git a/test/safe_parse_date_time_test.dart b/test/safe_parse_date_time_test.dart index 48ee85e..18bc938 100644 --- a/test/safe_parse_date_time_test.dart +++ b/test/safe_parse_date_time_test.dart @@ -2,8 +2,8 @@ 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); @@ -11,18 +11,23 @@ void main() { 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)); + }); }); }