I have a task to display remaining months and days for booked cruise. I have tried something but it is not as per the requirements. Future Date is fetch from API and need to compare it with current date to get difference. I have attach image with my tried code.
DateTime received from API
2021-10-05T16:30:00Z
Tried Code
final date1 = DateTime.now().toUtc();
final DateTime date2 = DateTime.parse(date).toUtc();
final difference = date2.difference(date1).inDays;
final month1 = date1.month.toInt();
final month2 = date2.month.toInt();
final monthDiff = month1 - month2;
final daysDiff = difference - (monthDiff * 30);
print(difference);
print("monthDiff $monthDiff");
print("daysDiff $daysDiff");
return difference.toString();
CodePudding user response:
This is what I do. There is a problem that I define a month
as 30 days.
void main(List<String> args) {
final date = '2021-10-05T16:30:00Z';
final date1 = DateTime.now();
final date2 = DateTime.parse(date);
final difference = date2.difference(date1);
final monthDiff = (difference.inDays / 30).floor();
final daysDiff = difference.inDays % 30;
print(difference);
print('monthDiff $monthDiff');
print('daysDiff $daysDiff');
print(difference);
}
CodePudding user response:
Use the build-in function difference
:
Taken from the official documentation:
var berlinWallFell = DateTime.utc(1989, DateTime.november, 9);
var dDay = DateTime.utc(1944, DateTime.june, 6);
Duration difference = berlinWallFell.difference(dDay);
print(difference.inDays); //here you can use another getter