skip to Main Content

I’m currently creating an app to manage RSS feeds. Because there is no one set standard for the publication date of a post (there is, but for whatever reason a lot of feeds don’t follow it), I have multiple different types of date strings to parse.

I can parse these types of dates:

Thu, 01 Jan 1970 00:00:00 +0000

However, the date format used on NASA’s Breaking News feed resembles something like:

Thu, 01 Jan 1970 00:00 GMT

JavaScript’s date parser can easily parse both of these types, but I just can’t find a solution to this in Dart. I tried using the HttpDate parser, which is the most similar to this type, but it fails because there is no indicator of seconds in the format. I’m also worried that there are other date format types that I don’t know about that JavaScript can parse, but Dart can’t. What should I do?

2

Answers


  1. Here i use the INTL package to stablish two patterns, then i make a function to try to parse a date trying each of the patterns, if it fails to do so it throws an exception

    import 'package:intl/intl.dart';
    
    void main() {
      // Parse Thu, 01 Jan 1970 00:00:00 +0000
      final formatter1 = DateFormat('E, dd MMM yyyy HH:mm:ss Z');
      final date1 = formatter1.parse('Thu, 01 Jan 1970 00:00:00 +0000');
      print(date1); // 1970-01-01 00:00:00.000Z
      
      // Parse Thu, 01 Jan 1970 00:00 GMT
      final formatter2 = DateFormat('E, dd MMM yyyy HH:mm zzz');
      final date2 = formatter2.parse('Thu, 01 Jan 1970 00:00 GMT');
      print(date2); // 1970-01-01 00:00:00.000Z
    }
    
    DateTime parseDate(String dateString) {
      final formatter1 = DateFormat('E, dd MMM yyyy HH:mm:ss Z');
      final formatter2 = DateFormat('E, dd MMM yyyy HH:mm zzz');
      
      try {
        return formatter1.parse(dateString);
      } catch (_) {}
      
      try {
        return formatter2.parse(dateString);
      } catch (_) {}
      
      throw Exception('Failed to parse date: $dateString');
    }
    Login or Signup to reply.
  2. you can use timezone to convert DateTime To TZDateTime

    import 'package:timezone/timezone.dart' as tz;
    
    ...
    
    DateTime dt = DateTime.now(); //Or whatever DateTime you want
    final tzdatetime = tz.TZDateTime.from(dt, tz.local); //could be var instead of final 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search