format method
Formats the current date-time object into a custom string pattern.
This method replaces specific placeholders in the given pattern with the corresponding date-time components, such as year, month, day, hour, minute, second, and more.
Supported Pattern Placeholders:
yyyy
→ Full year (e.g.,2025
)yy
→ Two-digit year (e.g.,25
)MMMM
→ Full month name (e.g.,February
)MMM
→ Abbreviated month name (e.g.,Feb
)MM
→ Two-digit month (e.g.,02
)M
→ Single-digit month (e.g.,2
)dd
→ Two-digit day (e.g.,05
)d
→ Single-digit day (e.g.,5
)EEEE
→ Full weekday name (e.g.,Tuesday
)EEE
→ Abbreviated weekday name (e.g.,Tue
)HH
→ 24-hour format (e.g.,17
)H
→ 24-hour format without leading zero (e.g.,5
)hh
→ 12-hour format (e.g.,05
)h
→ 12-hour format without leading zero (e.g.,5
)mm
→ Two-digit minutes (e.g.,09
)m
→ Single-digit minutes (e.g.,9
)ss
→ Two-digit seconds (e.g.,07
)s
→ Single-digit seconds (e.g.,7
)SSS
→ Milliseconds (e.g.,007
)a
→ AM/PM (e.g.,PM
)Z
→ Time zone offset (e.g.,+0530
)z
→ Time zone name (e.g.,IST
)Q
→ Quarter of the year (e.g.,1
,2
,3
,4
)DD
→ Day of the year, three-digit (e.g.,036
)D
→ Day of the year (e.g.,36
)ww
→ ISO week number, two-digit (e.g.,06
)w
→ ISO week number (e.g.,6
)u
→ ISO weekday number (1
= Monday,7
= Sunday)
Example Usage:
final date = DateTime(2025, 2, 5, 17, 54);
print(date.format(pattern: 'd MMMM, yyyy at h:mm a Q'));
// Output: "5 February, 2025 at 5:54 PM 1"
Implementation
String format({String pattern = 'dd-MM-yyyy'}) {
final isPM = hour >= 12;
final hour12 = hour % 12 == 0 ? 12 : hour % 12;
String formatted = pattern;
final patternMap = {
'yyyy': year.toString(),
'yy': year.toString().substring(2),
'MMMM': monthName(),
'MMM': monthName(isHalfName: true),
'MM': month.addZeroPrefix().validate(),
'M': month.toString(),
'dd': day.addZeroPrefix().validate(),
'd': day.toString(),
'EEEE': weekdayName(),
'EEE': weekdayName(isHalfName: true),
'HH': hour.addZeroPrefix().validate(),
'H': hour.toString(),
'hh': hour12.addZeroPrefix().validate(),
'h': hour12.toString(),
'mm': minute.addZeroPrefix().validate(),
'm': minute.toString(),
'ss': second.addZeroPrefix().validate(),
's': second.toString(),
'SSS': millisecond.toString().padLeft(3, '0'),
'a': isPM ? 'PM' : 'AM',
'Z': timeZoneOffSet(),
'z': timeZoneName,
'Q': ((month - 1) ~/ 3 + 1).toString(),
'DD': dayOfYear().toString().padLeft(3, '0'),
'D': dayOfYear().toString(),
'ww': weekOfYear().addZeroPrefix().validate(),
'w': weekOfYear().toString(),
'u': weekday.toString(),
};
// Replace using regex to avoid unwanted replacements
patternMap.forEach((key, value) {
formatted = formatted.replaceAllMapped(
RegExp(r'\b' + key + r'\b'), (match) => value);
});
return formatted;
}