How to Subtract two Dates in Flutter & Dart

Last updated on May 28, 2022 A Goodman Loading... Post a comment

In Flutter and Dart, you can subtract two dates by using the DateTime.difference method. The result is a duration.

Example:

void main() {
  final DateTime dateOne = DateTime(2022, 8, 30, 16, 59, 59);
  final DateTime dateTwo = DateTime(1980, 4, 29, 13, 45, 45);

  final Duration duration = dateOne.difference(dateTwo);
  print("${duration.inHours} hours");
}

Output:

 371115 hours

The DateTime class also has a method named subtract. However, this one isn’t used for subtracting two dates but used for subtracting a duration from a given date. The result is a date.

Example:

void main() {
  final date = DateTime.now();
  final result =
      date.subtract(const Duration(days: 1001, hours: 10, minutes: 48));
  print(result);
}

Output:

2019-08-31 04:27:01.494933

Note: You’ll get a different result from mine because DateTime.now gives you a different date each time you execute the code.

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like