How can I get the difference between 2 times?

7,641

Solution 1

you can find the difference between to times by using:

DateTime.now().difference(your_start_time_here);

something like this:

var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.

example from DartPad:

void main() {
  
    final startTime = DateTime(2020, 02, 20, 10, 30);
    final currentTime = DateTime.now();
  
    final diff_dy = currentTime.difference(startTime).inDays;
    final diff_hr = currentTime.difference(startTime).inHours;
    final diff_mn = currentTime.difference(startTime).inMinutes;
    final diff_sc = currentTime.difference(startTime).inSeconds;
  
    print(diff_dy);
    print(diff_hr);
    print(diff_mn);
    print(diff_sc);
}

Output: 3, 77, 4639, 278381,

Hope this helped!!

Solution 2

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 3

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;
}
Share:
7,641
Sarah Abouyassine
Author by

Sarah Abouyassine

Ambitious girl who likes to work in a dynamic environment where I will have the opportunity to face challenges. I seek to use my educational knowledge, and contribute to the improvement of the group through my know-how, my creativity and hard work.

Updated on December 08, 2022

Comments

  • Sarah Abouyassine
    Sarah Abouyassine over 1 year

    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(
    
    .............
    
    
  • Sarah Abouyassine
    Sarah Abouyassine about 4 years
    YEAAAAH thank you very much its really helpful .. I tried to get the year, month and day of the same day of now and extract the hour and minute of my variable to form the startTime so the difference between it and the DateTime.now() gives me the correct value .. TY so much for your help
  • Sarah Abouyassine
    Sarah Abouyassine about 4 years
    DateFormat fd = DateFormat("HH:mm"); DateTime tt = fd.parse(snapshot.documents[i].data['until']); var diff = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, tt.hour, tt.minute, tt.second) .difference(DateTime.now());
  • Mahesh Jamdade
    Mahesh Jamdade over 2 years
    You should store this value DateTime.now().difference(time) in a a variable to prevent recalculation.
  • LearnFlutter
    LearnFlutter about 2 years
    Hi, im having a similar problem here and I cant figure it out stackoverflow.com/questions/71587597/…