1

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?

EleKtr1X
  • 31
  • 1
  • 6
  • It is impossible to parse arbitrary date/time strings without ambiguity. (See the comments to https://stackoverflow.com/q/76142170/). If you want to specify a list of date/time formats that you can accept, see https://stackoverflow.com/q/71970859/ and https://stackoverflow.com/q/72059158/. – jamesdlin May 02 '23 at 21:25
  • Okay, but let's say I just want to parse those two types. How would I get the timezone? Timezones aren't implemented for DateFormat as far as I know. – EleKtr1X May 02 '23 at 22:00
  • Then see https://stackoverflow.com/q/64141573/ – jamesdlin May 03 '23 at 00:18

2 Answers2

0

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');
}
0

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 
Irvan Thole
  • 165
  • 9