Dart
Date helpers
Add DateTime processing methods.
The formatDate method
We'll write a formatDate method to show dates in one form. formatDate(year, month, day) returns a string in YYYY-MM-DD form; single digit months and days are zero padded.
Example: formatDate(2024, 5, 1) → '2024-05-01'. For month and day we use padLeft(2, '0'): 5.toString().padLeft(2, '0') gives '05'. padLeft pads the string to a given length; missing characters on the left are filled with the given character. This lets us format dates in one line.
String interpolation
formatDate joins year, month and day into a single string. In Dart two paths are common for string joining: the + operator and string interpolation.
Example: '$year-$m-$d'. Here $year, $m and $d are embedded directly into the string. Hyphens are written as is. This shape is more readable than the + operator: year.toString() + '-' + m + '-' + d. Interpolation gives a clean form, especially when many variables mix with literal characters.
Exercise Add formatDate to Helper
Keep the existing Helper class. Add a String formatDate(int year, int month, int day) method to the class. In the body write var m = month.toString().padLeft(2, '0');, var d = day.toString().padLeft(2, '0'); and return '$year-$m-$d';. In main, create an instance with var h = Helper(); and call print(h.formatDate(2024, 5, 1)).
Show example solution
class Helper {
final String version;
Helper() : version = '1.0';
String slugify(String text) {
return text.toLowerCase().replaceAll(' ', '-');
}
int clamp(int value, int min, int max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
String formatDate(int year, int month, int day) {
var m = month.toString().padLeft(2, '0');
var d = day.toString().padLeft(2, '0');
return '$year-$m-$d';
}
}
void main() {
var h = Helper();
print(h.formatDate(2024, 5, 1));
}
Test yourself
-
Match the formatDate parts
- formatDate
- Method name
- padLeft(2, '0')
- Zero padding
- 2024-05-01
- Output
-
Complete the padLeft call
var m = month.toString().____(2, '0');
Show answer
var m = month.toString().padLeft(2, '0');
-
What does formatDate(2024, 5, 1) return?
- 2024-5-1
- 2024/05/01
- 05-01-2024
- 2024-05-01
Show answer
2024-05-01 — padLeft pads month and day with zeros; the separator is a hyphen.
Next lesson: Putting it together