15

I have a date and want to display the date with the suffix th, st, rd, etc.

Here is my dart code.

int year = date.year;
int month = date.month;
int day = date.day;

DateTime dateSelected = new DateTime(year, month, day);
var formatter = new DateFormat('EEEE MMMM dd, yyyy');
displayDate = formatter.format(dateSelected);

This displays dates as "Wednesday April 23, 2014" for example, but I need "Wednesday April 23rd, 2014".

I'm using the intl package.

import 'package:intl/intl.dart';

Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
Phil
  • 39,334
  • 32
  • 103
  • 162
  • Maybe it is part of the intlx package, but I don't know – Fox32 Apr 26 '14 at 09:28
  • If this is only going to need to appear in English speaking countries, I recommend something similar to this answer for Java http://stackoverflow.com/questions/4011075/how-do-you-format-the-day-of-the-month-to-say-11th-21st-or-23rd-in-java – davecom Apr 26 '14 at 15:18
  • Remember it's not always necessary to write it like that ```One writes January 1, but says “January first.” One writes November 12, but says “November twelfth.” The only time to use the “th, nd, rd” and “st” with numbers is with ordinal numbers.``` https://www.dailywritingtips.com/january-1-doesnt-need-an-st/ – Er1 Jan 07 '21 at 09:47

4 Answers4

14
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)}'
Johngorithm
  • 319
  • 2
  • 8
9

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
Jama Mohamed
  • 2,239
  • 4
  • 22
  • 36
8

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.

lefloh
  • 10,388
  • 3
  • 27
  • 49
2

May not be better...but shorter

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