How can I add working days to a specific date (Flutter)? - flutter

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)

Related

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

DateTime.isAtSameMomentAs() is not working for me

I am trying to do a simple comparison between 2 DateTime dates. I am using the .isAtSameMomentAs() comparison but it is never true when both dates are 2021.07.02.
What am I doing wrong?
List<Event> _getEventsForDay(DateTime day) {
// kEvents is a linkedHashMap
for (int i = 0; i < eventDoc.length; i++ ) {
if (day.isAtSameMomentAs(eventDoc[i].eventDate)) {
print(day);
}
}
}
In the image below the top date and the bottom dates are the dates I am trying to compare.
Try using compareTo method
var temp = DateTime.now().toUtc();
var date1 = DateTime.utc(temp.day,temp.year,temp.month);
//you can add today's date below
var date2 = DateTime.utc(2,07,21);
if(date2.compareTo(date1)== 0){
print('true');
}else{
print('false');
}
I solved the problem with this code
if (day.year == eventDate.year && day.day == eventDate.day && day.month == eventDate.month)
It works for now but I still think there is a better way.

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)

How to determine which DateTime is greater or less than the other

How it should work:
Make sure that today is between 2020-April-01(timestampValidFrom - firebase timestamp format) and 2020-April-05(timestampValidTo).
I need like this query.
1)
timestampValidFrom <= today >= timestampValidTo
or
2)
.where('timestampValidFrom', isGreaterThanOrEqualTo: Timestamp.now())
.where('timestampValidTo', isLessThanOrEqualTo: Timestamp.now())
I have tried to fix this solution, but it does not work.
DateTime now = DateTime.now();
DateTime yesterday,tomorrow;
yesterday = DateTime(now.year, now.month, now.day); // today 12.00.00
tomorrow = DateTime(now.year, now.month, now.day +1); //tomorrow 12.00.00
if(yesterday.isAfter(snapshot.data[index].timestampValidFrom.toDate())
|| snapshot.data[index].timestampValidFrom.toDate().isBefore(tomorrow)
&& yesterday.isBefore(snapshot.data[index].timestampValidTo.toDate())
|| snapshot.data[index].timestampValidTo.toDate().isAfter(tomorrow)) {
// show widget
} else {
//emplty widget
}
you can use DateTime.compareTo to perform greater-than-or-equal-to or less-than-or-equal-to checks:
var today = DateTime.now();
var isValid = today.compareTo(timestampValidFrom) >= 0 &&
today.compareTo(timeStampValidTo) <= 0;
You can define operator <= and operator >= on DateTime as extensions to make this comparison easier to read. package:basics does this for you:
import 'package:basics/basics.dart';
...
var today = DateTime.now();
var isValid = today >= timestampValidFrom && today <= timestampValidTo;
Use the difference method.
final yesterday = DateTime(now.year, now.month, now.day); // today 12.00.00
final tomorrow = DateTime(now.year, now.month, now.day +1); //tomorrow 12.00.00
int diffInDays = tomorrow.difference(yesterday).inDays;
if (diffInDays == 0){
//custom code
print( "same day");
} else if( diffInDays > 0 ) {
// custom code
print("tomorrow is greater ");
} else{
// custom code
print(" yesterday is less" );
}
Hope it helps!
You can simply check whether the current date is between the promotion start date and end date, if yes show the promotion else hide it.
DateTime now = DateTime.now();
DateTime beg = snapshot.data[index].timestampValidFrom.toDate();
DateTime end = snapshot.data[index].timestampValidTo.toDate();
if(now.isAfter(beg) && now.isBefore(end)){
print('show promo');
} else{
print('remove promo');
}
It won't include the start & end date. For including the start date, check the following if statement:
if((now.difference(beg).inMinutes >= 0 || now.isAfter(beg)) && (now.isBefore(end) || now.difference(end).inMinutes <= 0)){
print('show promo');
}else{
print('remove promo');
}

Get current Week of the Month as a Number

How do I get the current week of the month as a number in Dart? I need to create some sort of calender with a week view where it says something like "2. Week of January"
You can use DateTime().now() to get the current time and date of the system or today's date also. Here is the code snippet below:
// Current date and time of system
String date = DateTime.now().toString();
// This will generate the time and date for first day of month
String firstDay = date.substring(0, 8) + '01' + date.substring(10);
// week day for the first day of the month
int weekDay = DateTime.parse(firstDay).weekday;
DateTime testDate = DateTime.now();
int weekOfMonth;
// If your calender starts from Monday
weekDay--;
weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
print('Week of the month: $weekOfMonth');
weekDay++;
// If your calender starts from sunday
if (weekDay == 7) {
weekDay = 0;
}
weekOfMonth = ((testDate.day + weekDay) / 7).ceil();
print('Week of the month: $weekOfMonth');
Alternatively, if are looking for a complete implementation of the calender month UI then click here
My Answer is impaired from #dblank answer
extension DateTimeExtension on DateTime {
int get weekOfMonth {
var date = this;
final firstDayOfTheMonth = DateTime(date.year, date.month, 1);
int sum = firstDayOfTheMonth.weekday - 1 + date.day;
if (sum % 7 == 0) {
return sum ~/ 7;
} else {
return sum ~/ 7 + 1;
}
}
}
Then use it like this:
var wom = DateTime.now().weekOfMonth;
extension DateTimeExtension on DateTime {
int get weekOfMonth {
var wom = 0;
var date = this;
while (date.month == month) {
wom++;
date = date.subtract(const Duration(days: 7));
}
return wom;
}
}
Then use it like this:
var wom = DateTime.now().weekOfMonth;