I assume that by DateTime<List>
you mean List<DateTime>
. In this case, you can combine List.map
with DateTime.parse
to quickly convert the entire string list into a list of Datetime
objects.
final strings = [
'2022-01-01T12:00:00Z',
'2022-01-02T12:00:00Z',
'2022-01-03T12:00:00Z',
'2022-01-04T12:00:00Z',
];
final dates = strings.map((s) => DateTime.parse(s)).toList();
If you wanted to be concise, you could reference DateTime.parse
directly so as to eliminate the lambda function entirely:
final dates = strings.map(DateTime.parse).toList();
Note that this assumes that all of the strings in the list are valid date-time strings in a format that DateTime.parse
can recognize (such as an ISO-8601 timestamp). If you can't guarantee that will always be the case, instead of DateTime.parse
, you want to use DateTime.tryParse
. However, tryParse
will return a DateTime?
instead of a DateTime
(meaning it can be null), so if you don't want that, you will need to do a bit more work on the list to filter out the nulls:
final strings = [
'2022-01-01T12:00:00Z',
'2022-01-02T12:00:00Z',
'2022-01-03T12:00:00Z',
'asdfasd',
'2022-01-04T12:00:00Z',
];
// Results in a List<DateTime?> with bad strings becoming null
final dates = strings.map(DateTime.tryParse).toList();
// Results in a List<DateTime> with bad strings filtered out
final dates = strings.map(DateTime.tryParse)
.where((dt) => dt != null)
.cast<DateTime>()
.toList();