Home > Software engineering >  how to subtract two different times in flutter
how to subtract two different times in flutter

Time:08-24

I want to subtract two different times in flutter for example

String time1 = "07:00";
String time2 = "08:12";

String time3 = time2 - time1;
//result will be 01:12

this is just a sample data explanation of what I want to achieve.

CodePudding user response:

See the sample code below. It prints 01:12 in the end.

Input Data:

String time1 = "07:00";
String time2 = "08:12";

Required Methods to be defined:

DateTime getTime(final String inputString) => DateFormat("hh:mm").parse(inputString);

String getString(final Duration duration) {
  String formatDigits(int n) => n.toString().padLeft(2, '0');
  final String minutes = formatDigits(duration.inMinutes.remainder(60));
  return "${formatDigits(duration.inHours)}:$minutes";
}

Computation

final String difference = getString(getTime(time2).difference(getTime(time1)));

Printing the result

print(difference); // 01:12

Have fun - but keep in mind to change the naming of the methods to better fit into your context.

CodePudding user response:

You should use Dart's built-in DateTime class and its DateTime.parse especially.

Documentation: https://api.dart.dev/stable/2.8.4/dart-core/DateTime/parse.html

CodePudding user response:

Try out below code for get difference between two times.

    var timeFormat = DateFormat("HH:mm"); //Time format
    var first = timeFormat.parse("10:40");
    var second = timeFormat.parse("18:20");
    print("Difference -->${second.difference(first)}");
    // prints Difference -->7:40

CodePudding user response:

Flutter|Dart provides a data type to handle dates : DateTime. So instead of using String, use DateTime :

DateTime time1 = DateTime.parse(your_date_here your_time);
DateTime time2 = DateTime.parse(your_date_here your_time);
DateTime time3 = time2.difference(time1);

If you want just the time part, you can format it using DateFormat from the intl package. You'll need to import it as follows :

import 'package:intl/intl.dart';

Then do the following:

String formattedTime = DateFormat.Hms().format(time1);
String formattedTime = DateFormat.Hms().format(time2);

Or you can just directly format the result (time3):

String formattedTime = DateFormat.Hms().format(time3);
  • Related