Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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';

like image 229
Phil Avatar asked Apr 26 '14 08:04

Phil


People also ask

How do you format month and day?

The day is written first and the year last in most countries (dd-mm-yyyy) and some nations, such as Iran, Korea, and China, write the year first and the day last (yyyy-mm-dd).

How do you format a date?

Press CTRL+1. In the Format Cells box, click the Number tab. In the Category list, click Date, and then choose a date format you want in Type.

What is ordinal date format?

This format of date is a combination of year plus a relative day number within the year, which is more correctly called an ordinal date. A typical example is 2013-348 in the format YYYYDDD. This is equivalent to a calendar date of December 14 th 2013.

What is the correct day month year format?

The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD. So if both Australians and Americans used this, they would both write the date as 2019-02-03. Writing the date this way avoids confusion by placing the year first. Much of Asia uses this form when writing the date.


2 Answers

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)}'
like image 125
Johngorithm Avatar answered Oct 22 '22 15:10

Johngorithm


May not be better...but shorter

static final _dayMap = {1: 'st', 2: 'nd', 3: 'rd'};
static String dayOfMonth(int day) => "$day${_dayMap[day] ?? 'th'}";
like image 45
mmaitlen Avatar answered Oct 22 '22 15:10

mmaitlen