Formatting Jalali dates
Format Persian dates in Dart with toString flags and format() patterns, using Persian month names (فروردین…) and weekday names.
Persian names
final date = PersianDate.fromGregorian(1979, 2, 11);
print(date.monthName); // بهمن
print(date.weekday); // 7 (DateTime.sunday)
print(date.weekdayName); // یکشنبهweekday follows DateTime.weekday (1 is Monday, 7 is Sunday), even though the Persian week starts on Saturday.
PersianDate.monthNames and PersianDate.weekdayNames hold the full lists.
toString
final date = PersianDate.fromGregorianString('2018-07-07T21:43:44.909Z');
print(date.toString()); // 1397/04/16
print(date.toString(showTime: true)); // 1397/04/16 21:43:44
print(date.toString(showTime: true, showSecond: false)); // 1397/04/16 21:43
print(date.toString(showDate: false, showTime: true)); // 21:43:44The flags are showDate, showTime, showHour, showMinute, and showSecond.
Every part is zero-padded to two digits.
Hiding everything throws ArgumentError.
Showing the time of a date created from Jalali values throws StateError, because it has no time of day.
format
final date = PersianDate.fromGregorian(2021, 3, 21);
print(date.format('d MMMM yyyy')); // 1 فروردین 1400
print(date.format('EEEE yyyy/MM/dd')); // یکشنبه 1400/01/01| Token | Output |
|---|---|
yyyy | year, at least four digits |
yy | last two digits of the year |
MMMM | Persian month name |
MM | month, two digits |
M | month |
dd | day, two digits |
d | day |
EEEE | Persian weekday name |
HH | hour (0 to 23), two digits |
H | hour (0 to 23) |
mm | minute, two digits |
m | minute |
ss | second, two digits |
s | second |
The longest token wins, and every other character is copied as is.
There is no escaping, so letters that form a token are always replaced: format('Month') gives 1onth.
Time tokens throw StateError for a date created from Jalali values.
In fromJson
class Item {
final String text;
final String? date;
Item(this.text, this.date);
factory Item.fromJson(Map<String, dynamic> json) {
final rawDate = json['date'] as String?;
return Item(
json['text'] as String,
rawDate == null
? null
: PersianDate.fromDateTime(DateTime.parse(rawDate).toLocal())
.format('yyyy/MM/dd HH:mm'),
);
}
}