I want to find the difference in days between two different datetimes in flutter.
in other words, i want to subtract two dates and get the difference between them
I found a way to do this in c# here. But unfortunately this doesn't apply for flutter.
Any help is appreciated
CodePudding user response:
You can use difference
method of DateTime
class to get the duration between two dates in dart.
DateTime date1 = new DateTime.now();
DateTime date2 = DateTime(2021, 1, 1);
print(date1.difference(date2).inDays); // Prints 356 days
CodePudding user response:
// get current date & time
DateTime startDate = DateTime.now();
String currentTime = formatISOTime(startDate);
//convert date to String
String formatISOTime(DateTime date) {
var duration = date.timeZoneOffset;
if (duration.isNegative)
return (date.toIso8601String()
"-${duration.inHours.toString().padLeft(2, '0')}:${(duration.inMinutes - (duration.inHours * 60)).toString().padLeft(2, '0')}");
else
return (date.toIso8601String()
" ${duration.inHours.toString().padLeft(2, '0')}:${(duration.inMinutes - (duration.inHours * 60)).toString().padLeft(2, '0')}");
}
//calculate time difference
String? timediffference = calculateTimeDifferenceBetween(
givenDate ?? '',
currentTime) ??
'',
static String? calculateTimeDifferenceBetween(
String? givenDate, String? currentTime) {
if (givenDate == null ||
givenDate.isEmpty ||
currentTime == null ||
currentTime.isEmpty) {
return "";
} else {
String gDate = givenDate.replaceAll('T', ' ');
String curTime = currentTime.replaceAll('T', ' ');
DateTime startParseDate =
new DateFormat("yyyy-MM-dd HH:mm:ss").parse(curTime);
DateTime endParseDate =
new DateFormat("yyyy-MM-dd HH:mm:ss").parse(gDate);
Duration diff = startParseDate.difference(endParseDate);
if (diff.inDays >= 1) {
return '${diff.inDays} day ago';
} else if (diff.inDays >= 30) {
return '${diff.inDays % 30} months ago';
} else if (diff.inDays >= 365) {
return '${diff.inDays % 365} years ago';
} else if (diff.inHours >= 1) {
return '${diff.inHours} hours ago';
} else if (diff.inHours < 1) {
if (diff.inMinutes >= 1) {
return '${diff.inMinutes} minutes ago';
} else if (diff.inMinutes < 1) {
return 'just now ';
} else {
return 'just now ';
}
} else {
return 'just now ';
}
}
}