5.8 C
New York
Tuesday, December 5, 2023

How to Subtract two Dates in Flutter & Dart

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


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");


 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.


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


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.Advertisements

Further reading:

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


Related Articles

Latest Articles