Home > Back-end >  How to convert a String with dates to DateTime? Flutter/Dart
How to convert a String with dates to DateTime? Flutter/Dart

Time:08-18

I have a string with 4 dates inside

I/flutter (27269): 2022-08-01 13:08
I/flutter (27269): 2022-08-01 12:54
I/flutter (27269): 2022-08-01 11:46
I/flutter (27269): 2022-07-13 12:42

i want to convert it to DateTime, i tried this DateTime.parse("myStringName"); but it stores only the last date.

CodePudding user response:

This should work:

void main(){
  const myString='I/flutter (27269): 2022-08-01 13:08 I/flutter (27269): 2022-08-01 12:54 I/flutter (27269): 2022-08-01 11:46 I/flutter (27269): 2022-07-13 12:42';

  final myStrings=myString.split('I/flutter (27269): ')..removeAt(0);

  for(final dateString in myStrings){
    var myDateString=dateString.replaceAll('-', '').trim();
    print(DateTime.parse(myDateString));
  }
}

CodePudding user response:

const String firstDate = '2012-02-27 13:27'; 
const String secondDate = '2002-02-27 14:05';

final date1 = DateTime.tryParse(firstDate);
print(date1);

final date2 = DateTime.tryParse(secondDate);
print(date2);

Output:

2012-02-27 13:27:00.000

2002-02-27 14:05:00.000

  • Related