THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial shows multiple ways to find the number of days between two dates.
There are multiple ways we can do
First Created two dates with DateTime constructor and now()
Next, find the difference between two dates using the difference() method. It returns the Duration object which returns the number of days using the inDays
property.
Syntax
Duration difference(DateTime other)
Similarly, you can call Duration.inHours to return the number of hours and divided by 24 to get the days to count.
Here is an example program to find differences in days between two dates.
void main() {
final date1 = DateTime(1990, 03, 03);
final date2 = DateTime.now();
final differenceDays = date2.difference(date1).inDays;
final differenceDays1= (date2.difference(date1).inHours/24).round();
print(differenceDays);
print(differenceDays1);
}
Output:
11724
11724
To get the Number of years counted between two dates, you can use
inDays` divided by 365.
void main() {
final date1 = DateTime(1990, 03, 03);
final date2 = DateTime.now();
final differenceDays = date2.difference(date1).inDays;
final differenceDays1 = (date2.difference(date1).inHours / 24).round();
final differenceYears = (date2.difference(date1).inDays / 365).floor();
print(differenceDays);
print(differenceDays1);
print(differenceYears);
}
Output:
32
Learned how to find the count of days and years between two dates.
🧮 Tags
Recent posts
How to Convert String to Int in swift with example How to Split a String by separator into An array ub swift with example How to disable unused code warnings in Rust example Golang Tutorials - Beginner guide Slice Examples Golang Array tutorials with examplesRelated posts