i created function in flutter using dart that takes Today date and see if it equal to today or not. and u can use for a week, month..etc
here it is
bool daysPassed(int timeStamp, int days) {
if (DateTime.now()
.difference(DateTime.fromMillisecondsSinceEpoch(timeStamp))
.inDays >=
days) {
return true;
}
return false;
}
so i used this function to see if a one day passed or not , if one day passed make all the variables from shared preference to zero, otherwise get the current variables
here is the logic that i made,
HOME.pref = await SharedPreferences.getInstance();
int? timeStamp = HOME.pref!.getInt('day_timestamp_values_changed');
int? timeStamp1Week = HOME.pref!.getInt('week_timestamp');
setState(() {
if (timeStamp != null) {
if (daysPassed(timeStamp, 1)) {
// 1 means if 1 day is passed
HOME.pref!.setDouble('currentCircleProgressValue', 0);
HOME.pref!.setDouble('currentCircleProgressValue2', 0);
HOME.pref!.setDouble('currentCircleProgressValue3', 0);
HOME.pref!.setInt('iii', 0);
if (HOME.Currentday != 0) {
HOME.Lastday = HOME.pref!.getInt('Currentday')!;
HOME.pref!.setInt('Currentday', 0);
}
} else {
HOME.currentCircleProgressValue =
HOME.pref!.getDouble('currentCircleProgressValue')!;
HOME.currentCircleProgressValue2 =
HOME.pref!.getDouble('currentCircleProgressValue2')!;
HOME.currentCircleProgressValue3 =
HOME.pref!.getDouble('currentCircleProgressValue3')!;
HOME.iii = HOME.pref!.getInt('iii')!;
HOME.Currentday = HOME.pref!.getInt('Currentday')!;
HOME.Lastday = HOME.pref!.getInt('Lastday')!;
}
}
the problem is when i test this out the variables after still the same. nothing happens the variables not initialize to zero.
Can u please help me out ?
Thank u
Related
I'm building a mobile client for a blog with a paid CMS that shows a number of articles all the time, plus a rotating article each week, and I've built a simple function to get the current week of the year and return a Boolean value if an article should be displayed this week:
bool displayArticle(StoredArticle article){
if (article.week < 0) {
return true;
}
DateTime now = DateTime.now();
DateTime janFirst = DateTime(now.year, 1, 1);
int weekNum = (now.difference(janFirst).inDays / 7).ceil();
if(article.week == weekNum || article.week == (weekNum - 1)){
return true;
}
return false;
}
I then use this function to filter a list of all the articles like so:
List<StoredArticle> articlessToDisplay = storedArticleObjs.where((article) => {
displayArticle(article)
}).toList();
This is all enclosed within a Stateful Widget.
However, using the function like this throws an error at the function call that The return type 'Set<bool>' isn't a 'bool', as required by the closure's context.
My first thought was that there was an issue with the displayArticle() function being a static member function to a stateful widget, but moving the function directly into the closure as follows did not impact the error.
List<StoredArticle> articlessToDisplay = storedArticleObjs.where((article) => {
if (article.week < 0) {
return true;
}
DateTime now = DateTime.now();
DateTime janFirst = DateTime(now.year, 1, 1);
int weekNum = (now.difference(janFirst).inDays / 7).ceil();
if(article.week == weekNum || article.week == (weekNum - 1)){
return true;
}
return false;
}).toList();
Next I thought it might be that the early return was confusing the inspector to belive it was returning multiple values, so I converted it to a single return function as follows, but that did nothing either.
bool displayArticle(StoredArticle article){
bool shouldDisplay = false;
if (article.week < 0) {
shouldDisplay = true;
}
DateTime now = DateTime.now();
DateTime janFirst = DateTime(now.year, 1, 1);
int weekNum = (now.difference(janFirst).inDays / 7).ceil();
if(article.week == weekNum || article.week == (weekNum - 1)){
shouldDisplay = true;
}
return shouldDisplay;
The only resources on similar issues have been referring to functions that return Future<T> instead of T. Putting aside the fact that my issue is with a Set<T> rather than a Future<T>, those errors have all been thrown by the return statement or the function definition rather than the function call.
I haven't been able to find any resources relating to this specific issue, though as I'm new to Flutter and Dart I suppose could be missing some specific terminology.
That being said, returning a set of the return type does not make any sense to me. Is this a quirk of implementation in a Stateful Widget?
The problem is that you have a few too many braces, and {"A"} is set-syntax in Dart.
You have:
storedArticleObjs.where((article) => {
displayArticle(article)
}).
Change that to:
storedArticleObjs.where((article) =>
displayArticle(article)
).
Note that the => function syntax doesn't use braces.
You could even probably write it more compactly using tear-offs like so:
storedArticleObjs.where(displayArticle).
I want to add the calulated working days to a specific date.
For example
I want to add 14 working days
date -> 08.17.2022 (it is input)
newDate -> 09.06.20222 (it is output)
I tried it with the code below but it didn't work as I want. What is my wrong? How can I do that?
Thanks in advance.
final workingDays = <DateTime>[];
final currentDate = DateTime.fromMicrosecondsSinceEpoch(
widget.siparisModel.siparisTarih.microsecondsSinceEpoch);
final orderDate = currentDate.add(Duration(days: 15));
DateTime indexDate = currentDate;
while (indexDate.difference(orderDate).inDays != 0) {
final isWeekendDay = indexDate.weekday == DateTime.saturday || indexDate.weekday == DateTime.sunday;
if (!isWeekendDay) {
workingDays.add(indexDate);
}
indexDate = indexDate.add(Duration(days: 15));
}
You could do something like this:
var newDate = DateTime(2022, 08, 17); // Copy from some "currentDate"
var numOfWeekdaysToAdd = 14;
while (numOfWeekdaysToAdd > 0) {
do {
newDate = newDate.add(Duration(days: 1));
} while (newDate.weekday == DateTime.saturday || newDate.weekday == DateTime.sunday);
numOfWeekdaysToAdd--;
}
Working DartPad demo:
https://dartpad.dev/?id=6ef6f4306944b350edfb77905239297e
If you want to, you could extend the "weekend-check" and make it more complex to also check for holidays in a specific locale. In that case I'd have a list of holiday-dates, and just add something like holidayDates.contains(newDate)
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
I am fetching a list of orders and storing the objects in a List. The object has a property called String deliveryTime and the times are in 'hh:mm a' format. I want to sort the list by the deliveryTime of the objects in Ascending order. I created a list of String that has the deliveryTime only and used bubble sort to sort them in ASCENDING order. But I am having trouble sorting the entire list of objects in that order.
NOTE: The list of object has some null & "ASAP" as their deliveryTime value.
Here's the incomplete code:
List<OnlineDeliveryOrder> getSortedOrdersList(
List<OnlineDeliveryOrder> orderList,
) {
List<OnlineDeliveryOrder> tempOrderList = [];
List<DateTime> sortedTimeList = [];
print("List Length before Sort: " + orderList.length.toString());
orderList.forEach((OnlineDeliveryOrder order) {
if (order.deliveryTime != null && order.deliveryTime != "ASAP")
sortedTimeList.add(DateFormat('hh:mm a').parse(order.deliveryTime));
});
sortedTimeList =
sortedTimeList.toSet().toList(); //Taking the unique times only
//Sorting times in asc order using bubble sort algorithm
bool sorted = false;
while (!sorted) {
sorted = true;
for (int i = 0; i < sortedTimeList.length - 1; i++) {
DateTime tempTime;
if (sortedTimeList[i].compareTo(sortedTimeList[i + 1]) == 1) {
// dt1.compareTo(dt2) == 1 if dt1 is a later date than dt2
tempTime = sortedTimeList[i];
sortedTimeList[i] = sortedTimeList[i + 1];
sortedTimeList[i + 1] = tempTime;
sorted = false;
}
}
}
// HOW DO I SORT THE ENTIRE LIST
print("List Length after Sort: " + tempOrderList.length.toString());
// String time = DateFormat('hh:mm a').format(element);
return tempOrderList;
}
Can anyone please guide me on how can I return the sorted list?
Why do you implement a sorting algorithm with O(n^2) time complexity by your own?
You can use
List<OnlineDeliveryOrder> getSortedOrdersList(List<OnlineDeliveryOrder> orderList){
var format = DateFormat('hh:mm a');
return List.of(orderList)..sort((a,b){
if(a.deliveryTime == null) return 1;
if(b.deliveryTime == null) return -1;
if(a.deliveryTime == 'ASAP') return 1;
if(b.deliveryTime == 'ASAP') return -1;
return format.parse(a.deliveryTime).compareTo(format.parse(b.deliveryTime));
});
}
This way, first all objects come with valid date, then with 'ASAP' and then with null as deliveryTime.
Or if you want it even more efficient without any package:
class SortObject extends Comparable<SortObject>{
static final DateFormat format = DateFormat('hh:mm a');
final OnlineDeliveryOrder order;
final DateTime? deliveryTime;
SortObject(this.order):this.deliveryTime=order.deliveryTime==null||order.deliveryTime=='ASAP'?null:format.parse(order.deliveryTime);
int compareTo(SortObject other){
if(order.deliveryTime == null) return 1;
if(other.order.deliveryTime == null) return -1;
if(order.deliveryTime == 'ASAP') return 1;
if(other.order.deliveryTime == 'ASAP') return -1;
return deliveryTime!.compareTo(other.deliveryTime!);
}
}
List<OnlineDeliveryOrder> getSortedOrdersList(List<OnlineDeliveryOrder> orderList){
return (orderList.map((a)=>SortObject(a)).toList()..sort((a,b){
return a.compareTo(b);
})).map((a)=>a.order).toList();
}
Or did I get the question wrong?
If there are errors in the code, I apologize. I just wrote it down.
I would recommend you to add in the OnlineDeliveryOrder class another attribute that stores the DateTime in addition to deliveryTime which does that as a String. Or you can store the time only as DateTime and not as String at all. If you receive the data as JSON, this is very easy to do. (This way you wouldn't need an extra class or a GroupedList).
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)