Flutter calculates the time difference between two dates

Flutter calculates the time difference between two dates


In our development, if we encounter the calculation of how many days are the difference between two dates, what method should be used to obtain it? If you need to know how many hours, minutes, and seconds are the difference between two dates, how do you calculate it?

In fact, in Flutter, it is very simple to calculate the difference between date and time, you need to use the difference function. The following examples illustrate.

Example

1. Calculate how many days are the difference between two dates?

var startDate = new DateTime(2020, 12, 20);
var endDate = new DateTime.now();
var days = endDate.difference(startDate).inDays;

2. Calculate how many hours are the difference between two dates?

var startDate = new DateTime(2020, 12, 20);
var endDate = new DateTime.now();
var hours = endDate.difference(startDate).inHours;

3. Calculate how many minutes are the difference between two dates?

var startDate = new DateTime(2020, 12, 20);
var endDate = new DateTime.now();
var minutes = endDate.difference(startDate).inMinutes;

Everyone, is it very simple? As long as we use the difference method, we can get the difference in all time units.

Source code analysis

In fact, the difference method of DateTime returns a Duration object.

What is Duration?

Duration is the class used to represent the time span (difference value), such as 27 days, 4 hours, 12 minutes and 3 seconds. Duration provides many methods of time unit conversion and time addition and subtraction calculation methods, which is very convenient to use.

Note that Duration represents the time difference, and it can be a negative number.

Its properties:

  final int _duration;

It is the difference between two times, the unit is microseconds, it is the most core attribute.

InDays, inHours, inMinutes, etc., are all the get methods of Duration, and the result is obtained internally by dividing the _duration attribute by the corresponding time unit.

For example, the number of days is calculated:

  int get inDays => _duration ~/ Duration.microsecondsPerDay;

Is it very convenient, and Duration can be used in many scenes such as animation.


**PS: For more exciting content, please check --> "Flutter Development"
**PS: For more exciting content, please check --> "Flutter Development"
**PS: For more exciting content, please check --> "Flutter Development"

Guess you like

Origin blog.csdn.net/u011578734/article/details/111997600