Home > Back-end >  How to trasfer a List<String> values to a DateTime<List> datetime values?? Flutter/Dart
How to trasfer a List<String> values to a DateTime<List> datetime values?? Flutter/Dart

Time:08-18

I have a List with some string values inside (undefined number of how many but they are dates) i want to convert these values to DateTime and then to store each one to this line:

specialDates:[DateTime(2022, 08, 16),DateTime(2022,08,03)]),

this line only accept DateTime values

CodePudding user response:

If that list have right strings, which could be converted into DateTime, you should follow this snip:

 specialDates = stringsL.map((element) => DateTime.parse(element)).toList();

CodePudding user response:

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();
  • Related