17.7 C
New York
Thursday, September 29, 2022

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.

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

AdvertisementsOutput:

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.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles