format method
Formats this date using a simple pattern.
Supported tokens: yyyy, yy, MM, M, dd, d,
HH, H, mm, ss, EEE (weekday abbr), EEEE (weekday full),
MMM (month abbr), MMMM (month full).
DateTime(2024, 3, 5).format('dd MMM yyyy') // '05 Mar 2024'
Implementation
String format(String pattern) {
const weekdayAbbr = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const weekdayFull = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
const monthAbbr = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const monthFull = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
// Scan the pattern left-to-right, matching the longest token first.
final tokenRe = RegExp(
r'yyyy|yy|MMMM|MMM|MM|M|dd|d|HH|H|mm|ss|EEEE|EEE|.',
);
return pattern.replaceAllMapped(tokenRe, (m) {
switch (m[0]) {
case 'yyyy':
return year.toString().padLeft(4, '0');
case 'yy':
return (year % 100).toString().padLeft(2, '0');
case 'MMMM':
return monthFull[month - 1];
case 'MMM':
return monthAbbr[month - 1];
case 'MM':
return month.toString().padLeft(2, '0');
case 'M':
return month.toString();
case 'dd':
return day.toString().padLeft(2, '0');
case 'd':
return day.toString();
case 'HH':
return hour.toString().padLeft(2, '0');
case 'H':
return hour.toString();
case 'mm':
return minute.toString().padLeft(2, '0');
case 'ss':
return second.toString().padLeft(2, '0');
case 'EEEE':
return weekdayFull[weekday - 1];
case 'EEE':
return weekdayAbbr[weekday - 1];
default:
return m[0]!;
}
});
}