Alessandro Buscema
Alessandro Buscema

Reputation: 91

Time with flutter

I am totally new with flutter and I do not understand how can I resolve a problem. I'm actually working to a kart race app and:

  1. I need to read a string like 1:02.456
  2. Convert in some kind of time
  3. Compare with another string similar to first one
  4. Go to do something

es:

blap = null;
if(1:02.456 < 1:03.589){
    blap = '1:02.456';
} else {
    blap = '1:03.589;
}

I read on the web that I ca use the class DateTime, but every time I try to convert the string in an object of that class, I do not get wat I want.

There is a better way? Thank you.

Upvotes: 0

Views: 118

Answers (1)

Lorenzo Cutrupi
Lorenzo Cutrupi

Reputation: 720

If you are working on a kart race app probably you need to use Duration, not DateTime.

This is one way to convert a string like yours into Duration

 Duration parseDuration(String s) {
  int hours = 0;
  int minutes = 0;
  int micros;
  List<String> parts = s.split(':');
  if (parts.length > 2) {
    hours = int.parse(parts[parts.length - 3]);
  }
  if (parts.length > 1) {
    minutes = int.parse(parts[parts.length - 2]);
  }
  micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
  return Duration(hours: hours, minutes: minutes, microseconds: micros);
}

Then, to compare two Duration in the way you wanted, this is an example:

String blap;
Duration time1=Duration(hours: 1),time2=Duration(hours: 2);
if(time1.compareTo(time2)<0){
  //time2 is greater than time1
  blap=time1.toString();
}else{
  blap=time2.toString();
}

Upvotes: 1

Related Questions