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';
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).
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.
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.
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.
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'}";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With