6

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(

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

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Sarah Abouyassine
  • 169
  • 1
  • 2
  • 13
  • I think this question is well explained here: https://stackoverflow.com/questions/52713115/flutter-finding-difference-between-two-dates – isa türk Feb 23 '20 at 13:34
  • Yeah actually i've already checked this answer and it's for the difference between 2 dates, i tried to use the same solution for the times but it didn't work – Sarah Abouyassine Feb 23 '20 at 13:41
  • Can you post the code you tried – isa türk Feb 23 '20 at 13:47
  • ```Duration t = DateTime.parse(snapshot.documents[i].data['from']).difference(DateTime.now());``` And the result is only the value of the first one wich is 18:00 – Sarah Abouyassine Feb 23 '20 at 13:54
  • Let's try this: Give me the value of snapshot.documents[i].data['from'], give the value of Datetime.now() and Give the value of t.inSeconds. So I can reproduce the situation. Otherwise I can not do anything – isa türk Feb 23 '20 at 14:43
  • okey so: value of snapshot.documents[i].data['from'] is 18:00 value of Datetime.now() is 15:50 t.inSeconds gives me 18:00 – Sarah Abouyassine Feb 23 '20 at 14:50

5 Answers5

20

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!!

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Abdelbaki Boukerche
  • 1,602
  • 1
  • 8
  • 20
  • 1
    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 Feb 23 '20 at 15:28
  • `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());` – Sarah Abouyassine Feb 23 '20 at 15:30
3

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');
Rudresh Narwal
  • 2,740
  • 3
  • 11
  • 21
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;
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Major Akash
  • 189
  • 5
  • Hi, im having a similar problem here and I cant figure it out https://stackoverflow.com/questions/71587597/create-timer-with-given-data/71587948?noredirect=1#comment126540887_71587948 – LearnFlutter Mar 24 '22 at 08:43
1

You can use this approch

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

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

Braken Mohamed
  • 194
  • 1
  • 16
Shailendra Rajput
  • 2,131
  • 17
  • 26
0

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));
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204