'How can I get the difference between 2 times?

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now(). I tried all methods difference, subtract, but nothing works!

Please help me to get the exact duration between those 2 times. I need this for a Count Down Timer.

This is an overview of my code:

.......

class _ActualPositionState extends State<ActualPosition>
    with TickerProviderStateMixin {
  AnimationController controller;
  bool hide = true;
  var doc;

  String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  @override
  void initState() {
    super.initState();
    var d = Firestore.instance
        .collection('users')
        .document(widget.uid);
    d.get().then((d) {
      if (d.data['parking']) {
        setState(() {
          hide = false;
        });
        Firestore.instance
            .collection('historyParks')
            .where('idUser', isEqualTo: widget.uid)
            .getDocuments()
            .then((QuerySnapshot snapshot) {
          if (snapshot.documents.length == 1) {
            for (var i = 0; i < snapshot.documents.length; i++) {
              if (snapshot.documents[i].data['date'] ==
                  DateFormat('EEE d MMM').format(DateTime.now())) {
                setState(() {
                  doc = snapshot.documents[i].data;
                });
                Duration t = DateTime.parse(snapshot.documents[i].data['until'])
                    .difference(DateTime.parse(
                        DateFormat("H:m:s").format(DateTime.now())));

                print(t);
              }
            }
          }
        });
      }
    });
    controller = AnimationController(
      duration: Duration(hours: 1, seconds: 10),
      vsync: this,
    );
    controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
  }

  double screenHeight;
  @override
  Widget build(BuildContext context) {
    screenHeight = MediaQuery.of(context).size.height;
    return Scaffold(

.............



Solution 1:[1]

You can use the DateTime class to find out the difference between two dates.

DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11'); 
DateTime dateTimeNow = DateTime.now();

final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');

final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');

Solution 2:[2]

Use this code:

var time1 = "14:00";
var time2 = "09:00";

Future<int> getDifference(String time1, String time2) async 
{
    DateFormat dateFormat = DateFormat("yyyy-MM-dd");
    
    var _date = dateFormat.format(DateTime.now());
    
    DateTime a = DateTime.parse('$_date $time1:00');
    DateTime b = DateTime.parse('$_date $time2:00');
    
    print('a $a');
    print('b $a');
    
    print("${b.difference(a).inHours}");
    print("${b.difference(a).inMinutes}");
    print("${b.difference(a).inSeconds}");
    
    return b.difference(a).inHours;
}

Solution 3:[3]

You can use this approch

getTime(time) {
  if (DateTime.now().difference(time).inMinutes < 2) {
    return "a few seconds ago";
  } else if (DateTime.now().difference(time).inMinutes < 60) {
    return "${DateTime.now().difference(time).inHours} min";
  } else if (DateTime.now().difference(time).inMinutes < 1440) {
    return "${DateTime.now().difference(time).inHours} hours";
  } else if (DateTime.now().difference(time).inMinutes > 1440) {
    return "${DateTime.now().difference(time).inDays} days";
  }
}

And You can call it getTime(time) Where time is DateTime Object.

Solution 4:[4]

To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.

If your goal is to show how long it will be from now to the next specified time in the local timezone:

import 'package:intl/intl.dart';

/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
  var now = DateTime.now();
  var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);

  // If the time precedes the current time, treat it as a time for tomorrow.
  if (nextTime.isBefore(now)) {
    // Note that this is not the same as `nextTime.add(Duration(days: 1))` across
    // DST changes.
    nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
  }
  return nextTime.difference(now);
}

void main() {
  var timeString = '14:00';

  // Format for a 24-hour time.  See the [DateFormat] documentation for other
  // format specifiers.
  var timeFormat = DateFormat('HH:mm');

  // Parsing the time as a UTC time is important in case the specified time
  // isn't valid for the local timezone on [DateFormat]'s default date.
  var time = timeFormat.parse(timeString, true);

  print(timeToNext(time.hour, time.minute, time.second));
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rudresh Narwal
Solution 2 Tomerikoo
Solution 3 Shailandra Rajput
Solution 4 jamesdlin