formatDate function
Writes date out according to format.
months and weekdays carry the short names, so a locale can say them its
own way. Both are indexed from January and from Monday.
Implementation
String formatDate(
DateTime date,
String format, {
List<String> months = _englishMonths,
List<String> weekdays = _englishWeekdays,
String am = 'AM',
String pm = 'PM',
}) {
final kept = _escaped
.allMatches(format)
.map((m) => m[0]!.substring(1, m[0]!.length - 1))
.toList();
var out = format.replaceAll(_escaped, _hole);
String pad(int value, int width) => '$value'.padLeft(width, '0');
final hour12 = date.hour % 12 == 0 ? 12 : date.hour % 12;
final isPm = date.hour >= 12;
// Names first: their letters would otherwise be eaten by the numeric
// passes — 'Mar' carries an 'a' and an 'r'.
out = out.replaceAll('MMM', _monthMark).replaceAll('EEE', _weekdayMark);
out = out
.replaceAllMapped(
RegExp('y+'),
(m) => m[0]!.length <= 2
? pad(date.year % 100, 2)
: pad(date.year, m[0]!.length),
)
.replaceAllMapped(RegExp('M+'), (m) => pad(date.month, m[0]!.length))
.replaceAllMapped(RegExp('d+'), (m) => pad(date.day, m[0]!.length))
.replaceAllMapped(RegExp('H+'), (m) => pad(date.hour, m[0]!.length))
.replaceAllMapped(RegExp('h+'), (m) => pad(hour12, m[0]!.length))
.replaceAllMapped(RegExp('m+'), (m) => pad(date.minute, m[0]!.length))
.replaceAllMapped(RegExp('s+'), (m) => pad(date.second, m[0]!.length))
.replaceAllMapped(
RegExp('w+'),
(m) => pad(weekOfYear(date), m[0]!.length),
)
.replaceAllMapped(
RegExp('Q+'),
(m) => pad(quarterOf(date), m[0]!.length),
)
.replaceAll('A', isPm ? pm.toUpperCase() : am.toUpperCase())
.replaceAll('a', isPm ? pm.toLowerCase() : am.toLowerCase());
out = out
.replaceAll(_monthMark, months[date.month - 1])
.replaceAll(_weekdayMark, weekdays[date.weekday - 1]);
var i = 0;
return out.replaceAllMapped(RegExp(_hole), (_) => kept[i++]);
}