normaliseTimestamp function
Normalises a timestamp string to ensure it contains the 'T' separator and optionally the 'Z' UTC timezone indicator.
Accepts timestamps in various formats:
- With 'T': "2025-01-21T23:05:42"
- Without 'T': "2025-01-21 23:05:42"
- With 'Z': "2025-01-21T23:05:42Z"
Parameters:
- timestamp: The timestamp string to normalize
- toIso: If true, ensures both 'T' separator and 'Z' suffix for full ISO format
Returns normalised timestamp string.
Implementation
String normaliseTimestamp(String timestamp, {bool toIso = false}) {
String result = timestamp;
// Add T separator if missing.
if (!result.contains('T')) {
result = result.replaceFirst(RegExp(r' (?=\d{2}:\d{2}:\d{2})'), 'T');
}
// Add Z suffix if requested and missing.
if (toIso && !result.endsWith('Z')) {
final dateTime = DateTime.parse(result).toUtc();
// toIso8601String() already includes the Z, so we don't need to add it again.
result = dateTime.toIso8601String();
}
return result;
}