Reputation: 359
I have 2 String in which I have hours and min
String1 = 2 HOUR 0 MIN
String2 = 1 HOUR 30 MIN
I need to check if I subtract String2
time with String1
values to go to negative or not.
For example, if I subtract String2
with String1
value will be in a time like 00:30
So basically I just need to check String2
is not greater then String1
, I am badly stuck on this how can i check it
Upvotes: 0
Views: 208
Reputation: 3584
I would consider first converting the Strings
to Duration
by parsing them. This can be done with a regexp for example:
/// Returns the duration associated with a string of
/// the form "XX HOUR XX MIN" where XX can be 1 or 2 digits
///
/// TODO: add check for fail safe
Duration _parseDateString(String dateString) {
// Make sure that this is correct, it really depends on the form of your input string
final dateStringRegexp = RegExp(r'(\d*) HOUR (\d*) MIN');
final match = dateStringRegexp.firstMatch(dateString);
final hours = int.parse(match!.group(1)!);
final minutes = int.parse(match.group(2)!);
return Duration(hours: hours, minutes: minutes);
}
Once you have this, it's pretty easy to compare the times:
final dateString1 = "2 HOUR 0 MIN";
final dateString2 = "1 HOUR 30 MIN ";
final duration1 = _parseDateString(dateString1);
final duration2 = _parseDateString(dateString2);
print(duration1.compareTo(duration2));
Upvotes: 0
Reputation: 17634
Is there a reason you're using Strings instead of Durations? The duration class has built in methods to add and subtract hours, mins, etc.
If you have to use strings, I would first convert them to Durations and add/subtract them.
Upvotes: 1