F

LutterAdda

How to get difference between two datetime in dart / flutter

A DateTime object is an object that represents a point in time. DateTime in dart is in dart:core library. The time zone of the object can be UTC(Universal coordinated time) or local time zone.

Uses of DateTime:🔗

1. To get the current time.

2. To compare time.

3. Parse timestamp to the DateTime object to perform all the operations available to the object.

4. Working with different time zones.

    DateTime dt1 = DateTime.parse("2023-05-17 12:00:00");
    DateTime dt2 = DateTime.parse("2017-05-17 12:00:00");
  
    Duration diff = dt1.difference(dt2);
    
    print('${diff.inDays} Days');
    print('${diff.inHours} Hours');
    print('${diff.inMinutes} Minutes');
    print('${diff.inSeconds} Seconds');
    print('${diff.inMilliseconds} Milliseconds');
    print('${diff.inMicroseconds} Microseconds');
    print('Is the time negative: ${diff.isNegative}');
                
datetime difference in dart
    //if your time is in timestamp
    DateTime dt1 = DateTime.fromMillisecondsSinceEpoch(1682243700000);
    DateTime dt2 = DateTime.fromMillisecondsSinceEpoch(1681984500000);
  
    Duration diff = dt1.difference(dt2);
    
    print('${diff.inDays} Days');
    print('${diff.inHours} Hours');
    print('${diff.inMinutes} Minutes');
    print('${diff.inSeconds} Seconds');
    print('${diff.inMilliseconds} Milliseconds');
    print('${diff.inMicroseconds} Microseconds');
    print('Is the time negative: ${diff.isNegative}');
datetime difference if timestamp