Date Comparison in Dart/Flutter - flutter

I am trying to compare two DateTimes in flutter and execute a particular function using if statements. However, I have been getting NoSuchMethodError.
Here is my code:
DateTime _myNowTime; DateTime _myClickTime
_getClickTime()async{ FirebaseUser currentUser = await
FirebaseAuth.instance.currentUser();
Firestore.instance.collection('user').document(currentUser.uid).snapshots().listen((event) {
if(event.data.isNotEmpty){ setState(() { _now_time = event['now_time'];
_click_time = event['click_time']; _myNowTime = _now_time.toDate(); _myClickTime = _click_time.toDate();
});
} }); }
I want to create a function:
checkTime(){
if(_myNowTime.compareTo(_myClickTime) >= 30 minutes){
//do something ...}
}

void main() {
var now = DateTime.now();
var yesterday = now.subtract(const Duration(days: 1));
if(now == yesterday) {
print("Dates are the same");
} else print("Dates are not the same");
}

Related

Flutter how to use multiple forloops

I am using this code but sometimes it runs the code in wrong order. Is it possible to wait for each for loop to finish before next one starts?
void changeWeek() {
for (int i = 0; i < newactivities.length; i++) {
int year = DateTime.now().year;
DateTime startDate = DateTime(year, 1, 1);
while (startDate.weekday != DateTime.monday) {
startDate = startDate.add(const Duration(days: 1));
}
for (String weekday in newactivities[i].daylistdone) {
int offset = (int.parse(weekday)) + (int.parse(currentweek) - 1) * 7;
DateTime donedate = startDate.add(Duration(days: offset));
oldDatesDone.add(Timestamp.fromDate(donedate));
}
for (String weekday in newactivities[i].daylist) {
int offset =
(int.parse(weekday) - 1) + (int.parse(currentweek) - 1) * 7;
DateTime notdonedate = startDate.add(Duration(days: offset));
oldDatesNotDone.add(Timestamp.fromDate(notdonedate));
}
for (var i in oldDatesDone) {
oldDatesNotDone.remove(i);
}
finaloldDatesDone = newactivities[i].weekdaysdone + oldDatesDone;
finaloldDatesNotDone = newactivities[i].weekdaysnotdone + oldDatesNotDone;
act.add({
'title': newactivities[i].title,
'days': newactivities[i].daylist,
'notificationidnumber': newactivities[i].notificationidnumber,
'daysdone': myData22,
'weekdaysdone': finaloldDatesDone,
'weekdaysnotdone': finaloldDatesNotDone,
'timelist': newactivities[i].timelist,
'time': newactivities[i].time
});
FirebaseFirestore.instance
.collection(widget.user.user.uid)
.doc(documentName)
.update({"activities": act});
}
}
Or can I do it in another way to solve the code?
Your Firebase update returns a Future, so it is an asynchronous operation. To preserve order of calls, you need to await the result of this call:
void changeWeek() async {
// ...
await FirebaseFirestore.instance
.collection(widget.user.user.uid)
.doc(documentName)
.update({"activities": act});
}
Note that you need do declare the changeWeek() function as async for this to work.

show data according to number of weeks

i have this ui what i want to achieve is that i want to show data according to the date and also if the number of week is selected 1 then i want to show that same data for seven days from that particular date and after that date i want to remove that item
void chooseDay(CalendarDayModel clickedDay) {
setState(() {
_lastChooseDay = _daysList.indexOf(clickedDay);
for (var day in _daysList) {
day.isChecked = false;
}
CalendarDayModel chooseDay = _daysList[_daysList.indexOf(clickedDay)];
chooseDay.isChecked = true;
dailyPills.clear();
for (var pill in allListOfPills) {
DateTime pillDate =
DateTime.fromMicrosecondsSinceEpoch(pill.time! * 1000);
int? week = pill.howManyWeeks;
int totalDays = week! * 7;
final extraDuration = Duration(days: totalDays);
final startDate = pillDate;
final newDateTime = startDate.add(extraDuration);
if (chooseDay.dayNumber == pillDate.day &&
chooseDay.month == pillDate.month &&
chooseDay.year == pillDate.year) {
log("first condition vhitra");
dailyPills.add(pill);
} else if (pillDate.day + 7 != newDateTime.day + 1) {
dailyPills.add(pill);
} else if (newDateTime.day.isLowerThan(chooseDay.dayNumber!)) {
setState(() {
dailyPills.clear();
});
}
}
dailyPills.sort((pill1, pill2) => pill1.time!.compareTo(pill2.time!));
});
}
this is what i tried need some insight here thanks

how to get difference(remaining time ) between '22:00:00' & '00:22:00' in flutter [duplicate]

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.

Flutter health: ^3.4.4 - getTotalStepsInInterval

i have problem with package health 3.4.4.
I need use this code a rebuild to other activities like BLOOD_OXYGEN or ACTIVE_ENERGY_BURNED :
This code is ok:
fetchStepBar() async {
int? steps;
int hour = 0;
int minute = 0;
int second = 0;
int millisecond = 0;
int microsecond = 0;
final midnight1 = selectedDate == null
? DateTime(now.year, now.month, now.day)
: DateTime(selectedDate!.year, selectedDate!.month, selectedDate!.day);
final stepstimefetch1 = selectedDate == null
? now
: DateTime(selectedDate!.year, selectedDate!.month, selectedDate!.day,
hour = 23, minute = 59, second = 59);
bool requested = await health.requestAuthorization([HealthDataType.STEPS]);
if (requested) {
try {
steps =
await health.getTotalStepsInInterval(midnight1, stepstimefetch1);
} catch (error) {
print("Caught exception in getTotalStepsInInterval: $error");
}
setState(() {
_nofStepsday = (steps == null) ? 0 : steps;
});
}
}
I see problem in: health.getTotalStepsInInterval
I tried rebuild code in class HealthFactory:
Future<int?> getTotalActive_energy_burnedInInterval(
DateTime startDate,
DateTime endDate,
) async {
final args = <String, dynamic>{
'startDate': startDate.millisecondsSinceEpoch,
'endDate': endDate.millisecondsSinceEpoch
};
final energy = await _channel.invokeMethod<int?>(
'getTotalActive_energy_burnedInInterval',
args,
);
return energy;
}
But!!! The problem I cannot solve is method channel -> 'getTotalActive_energy_burnedInInterval' It didn't works for me. I cannot definite this.
Can anybody help me solve this problem?
Thanks a lot

Flutter: Check if date is between two dates

I need to check date is between two dates or not.
I tried to search it but didn't got fruitful results.
May be you have seen such scenarios. So, seeking your advise.
Here is my code.
var service_start_date = '2020-10-17';
var service_end_date = '2020-10-23';
var service_start_time = '10:00:00';
var service_end_time = '11:00:00';
DateTime currentDate = new DateTime.now();
DateTime times = DateTime.now();
#override
void initState() {
super.initState();
test();
}
test() {
String currenttime = DateFormat('HH:mm').format(times);
String currentdate = DateFormat('yyyy-mm-dd').format(currentDate);
print(currenttime);
print(currentdate);
}
So, basically i have start date and end date. I need to check current date is falling between these two dates or not.
You can check before/after using 'isBefore' and 'isAfter' in 'DateTime' class.
DateTime startDate = DateTime.parse(service_start_date);
DateTime endDate = DateTime.parse(service_end_date);
DateTime now = DateTime.now();
print('now: $now');
print('startDate: $startDate');
print('endDate: $endDate');
print(startDate.isBefore(now));
print(endDate.isAfter(now));
I've made a series of extensions
extension DateTimeExtension on DateTime? {
bool? isAfterOrEqualTo(DateTime dateTime) {
final date = this;
if (date != null) {
final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
return isAtSameMomentAs | date.isAfter(dateTime);
}
return null;
}
bool? isBeforeOrEqualTo(DateTime dateTime) {
final date = this;
if (date != null) {
final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
return isAtSameMomentAs | date.isBefore(dateTime);
}
return null;
}
bool? isBetween(
DateTime fromDateTime,
DateTime toDateTime,
) {
final date = this;
if (date != null) {
final isAfter = date.isAfterOrEqualTo(fromDateTime) ?? false;
final isBefore = date.isBeforeOrEqualTo(toDateTime) ?? false;
return isAfter && isBefore;
}
return null;
}
}
I'm hoping they're self explanatory but obviously you can call them like
DateTime.now().isBefore(yourDate)
DateTime.now().isAfter(yourDate)
DateTime.now().isBetween(fromDate, toDate)
Don't forget to check if the day is the same as the one of the two dates also
by adding an or to the condition ex:
if ( start is before now || (start.month==now.month && start.day==now.day ...etc)