I would like to compare last_uploaded_time
with current time
.
How to check whether the two time is more or less than one minute?
bool compareTime(String starts) {
print(starts);
var start = starts.split(":");
DateTime currentDateTime = DateTime.now();
String currentTime =
DateFormat(DateUtil.TIME_FORMAT).format(currentDateTime);
print(currentTime);
var end = currentTime.split(":");
DateTime initDateTime = DateTime(
currentDateTime.year, currentDateTime.month, currentDateTime.day);
var startDate = (initDateTime.add(Duration(hours: int.parse(start[0]))))
.add(Duration(minutes: int.parse(start[1])));
var endDate = (initDateTime.add(Duration(hours: int.parse(end[0]))))
.add(Duration(minutes: int.parse(end[1])));
if (currentDateTime.isBefore(endDate) &&
currentDateTime.isAfter(startDate)) {
print("CURRENT datetime is between START and END datetime");
return true;
} else {
print("NOT BETWEEN");
return false;
}
}
Output
I/flutter (12908): 01:16
I/flutter (12908): 01:40
I/flutter (12908): NOT BETWEEN
CodePudding user response:
difference
not exactly working with minutes and seconds so you can use some custom algorithm like
import 'package:intl/intl.dart';
class IntelModel { static String timeSinceDate(DateTime date) { final now = DateTime.now(); final difference = now.toLocal().difference(date.toLocal());
if ((now.day - date.day) >= 8) { return 'A few weeks ago'; } else if ((now.day - date.day) >= 1) { return '${(now.day - date.day)} days ago'; } else if (now.day == date.day) { if (now.hour > date.hour) { if ((now.hour - date.hour) >= 2) { if (now.minute == date.minute) { return '${(now.hour - date.hour)} hours ago'; } else { var mins = now.minute - date.minute; if (mins > 1) { return '${(now.hour - date.hour)} h ${(now.minute - date.minute)} minutes ago'; } else { return '${(now.hour - date.hour) - 1} h ${60 mins} minutes ago'; } } } else if ((now.hour - date.hour) == 1) { int timeMin = now.minute (60 - date.minute); if (timeMin == 60) { return '1 hours ago'; } else if (timeMin >= 60) { return '1 h ${timeMin - 60} mins ago'; } else { return '$timeMin minutes ago'; } } } else if (now.hour == date.hour) { if (now.minute > date.minute) { return '${(now.minute - date.minute)} minutes ago'; } else if (date.minute == now.minute) { return '${(now.second - date.second)} seconds ago'; } } } else { return 'Error in time'; } } }
CodePudding user response:
void main() {
String getDifference(DateTime date){
Duration duration = DateTime.now().difference(date);
String differenceInMinutes = (duration.inMinutes).toString();
return differenceInMinutes;
}
String str = getDifference(DateTime.parse('2021-09-24'));
print (str);
}
i tried above code on dartpad, you can use this to compare tow dateTime variables. As per above example, you can get more options to compare for eg duration.inDays
,duration.inHours
,duration.inSeconds
etc.