Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse RFC 822 date (and make timezones work)

Tags:

dart

Just realized DateFormat is not caring about the time zone field. The two prints below will both output the same time.

import 'package:intl/intl.dart';

void main() {
  var formatter = DateFormat('EEE, dd MMM yyyy HH:mm:ss zzz');

  print(formatter.parse('Tue, 9 Jun 2020 19:46:10 +0000'));
  print(formatter.parse('Tue, 9 Jun 2020 19:46:10 +0200'));
}

Sadly, I can't use DateTime.parse instead as it only accepts ISO-8601 strings.

So that begs the question, how do I parse RFC 822 timestamps correctly in Dart?

like image 809
Marcus Avatar asked Nov 15 '25 17:11

Marcus


1 Answers

As per jamesdin's comment, I couldn't find any other way than to do this manually. Ended up with:

const MONTHS = {
  'Jan': '01',
  'Feb': '02',
  'Mar': '03',
  'Apr': '04',
  'May': '05',
  'Jun': '06',
  'Jul': '07',
  'Aug': '08',
  'Sep': '09',
  'Oct': '10',
  'Nov': '11',
  'Dec': '12',
};

DateTime parseRfc822(String input) {
  var splits = input.split(' ');
  var reformatted = splits[3] +
      '-' +
      MONTHS[splits[2]] +
      '-' +
      (splits[1].length == 1 ? '0' + splits[1] : splits[1]) +
      ' ' +
      splits[4] +
      ' ' +
      splits[5];

  return DateTime.tryParse(reformatted);
}
like image 52
Marcus Avatar answered Nov 17 '25 08:11

Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!