How do you format the day of the month to say “11th”, “21st” or “23rd” in Dart?

I don’t think that there’s build-in functionality for that. You could format the date like that:

format(DateTime date) {
  var suffix = "th";
  var digit = date.day % 10; 
  if ((digit > 0 && digit < 4) && (date.day < 11 || date.day > 13)) {  
    suffix = ["st", "nd", "rd"][digit - 1];
  }
  return new DateFormat("EEEE MMMM d'$suffix', yyyy").format(date);
}

Note: If you don’t want explicit the '01st' one d is enough.


Try out this package, Jiffy, inspired by momentjs.

Just simply add the do date pattern. See below

Jiffy([2014, 4, 23]).format("EEEE MMMM do, yyyy"); // Wednesday April 23rd, 2014

You can also add your DateTime object

Jiffy(DateTime(2014, 4, 23)).format("EEEE MMMM do, yyyy"); // Wednesday April 23rd, 2014

String getDayOfMonthSuffix(int dayNum) {
    if(!(dayNum >= 1 && dayNum <= 31)) {
      throw Exception('Invalid day of month');
    }

    if(dayNum >= 11 && dayNum <= 13) {
      return 'th';
    }

    switch(dayNum % 10) {
      case 1: return 'st';
      case 2: return 'nd';
      case 3: return 'rd';
      default: return 'th';
    }
}

The above method gets the suffix for you. You can use string concatenation or string interpolation to put together the format you want. e.g

'$day ${getDayOfMonthSuffix(day)}'

May not be better...but shorter

static final _dayMap = {1: 'st', 2: 'nd', 3: 'rd'};
static String dayOfMonth(int day) => "$day${_dayMap[day] ?? 'th'}";