Reputation: 50486
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';
Upvotes: 22
Views: 10726
Reputation: 1760
A SIMPLER/CLEANER SOLUTION:
Install the package moment_dart from your terminal.
flutter pub add moment_dart
Usage:
import 'package:moment_dart/moment_dart.dart';
.
.
.
final now = Moment.now();
print(now.format('dddd, Do'));
Output on your console:
flutter: Wednesday, 23rd
So to achieve exactly what you want, it would have to be:
print(now.format('dddd MMMM Do, YYYY'));
Output on your console:
flutter: Wednesday April 23rd, 2014
Upvotes: 2
Reputation: 3405
Try out this package, Jiffy, inspired by momentjs.
Just simply add the do
date pattern. See below
Jiffy.parseFromList([2014, 4, 23]).format("EEEE MMMM do, yyyy"); // Wednesday April 23rd, 2014
You can also add your DateTime object
Jiffy.parseFromDateTime(DateTime(2014, 4, 23)).format("EEEE MMMM do, yyyy"); // Wednesday April 23rd, 2014
Upvotes: 16
Reputation: 822
May not be better...but shorter
static final _dayMap = {1: 'st', 2: 'nd', 3: 'rd'};
static String dayOfMonth(int day) => "$day${_dayMap[day] ?? 'th'}";
Upvotes: 2
Reputation: 401
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)}'
Upvotes: 21
Reputation: 10961
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.
Upvotes: 8