How to show eras in DateFormat?

67 views Asked by At

I'm not looking for something powerful, for date format DateFormat is enough but i need to add A.D or B.C like in Anno Domini for dates.

Now i know it's not even a challenge to customize it but I'm looking for best way to do it with the official API so it can adapt to changes in the future.

1

There are 1 answers

3
jamesdlin On BEST ANSWER

package:intl's DateFormat class should be able to do with the G formatter:

import 'package:intl/intl.dart';

void main() {
  var date = DateTime(2021, 5, 6);
  print(DateFormat('yyyy-MM-dd G').format(date)); // Prints: 2021-05-06 AD
}

Note that negative years seem to be directly assumed to be BC; that is, a year of -1 seems to be treated as 1 BC. This might not be what you expect if you want year 0 to be invalid.