Skip to main content

prefer-date-format

added in: 1.7.0
⚙️🛠
Pro+

Warns when DateTime, values are formatted with toString instead of DateFormat.format().

⚙️ Config

Set ignored-invocations (default is empty) to ignore toString calls inside a specific invocation (example).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-date-format:
ignored-invocations:
- print

Example

❌ Bad:

void main() {
final DateTime dateTimeValue = DateTime.now();

// LINT: Prefer using 'DateFormat()' to convert a date to a string value.
final dateTimeString = dateTimeValue.toString();

// LINT: Prefer using 'DateFormat()' to convert a date to a string value.
final dateTimeString = '$dateTimeValue';
}

✅ Good:

void main() {
final DateTime dateTimeValue = DateTime.now();

final dateTimeString = DateFormat().format(dateTimeValue);
final dateTimeString = '${DateFormat().format(dateTimeValue)}';
}

Example with "ignored-invocations"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-date-format:
ignored-invocations:
- print

✅ Good:

void main() {
final DateTime dateTimeValue = DateTime.now();

print(dateTimeValue); // Correct, ignored
}