DateTime.isAtSameMomentAs() is not working for me - flutter

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.

Related

Flutter filter list by dates

So I am getting a Promo List from an API that has a dateStart and dateEnd field which returns YYYY-MM-DD String or null if it is empty. Now I want to compare/filter.
1- has dateStart=YYYY-MM-DD && has dateEnd=YYYY-MM-DD - is ok to render but if dateEnd == today or over then it wont show
2- has dateStart=YYYY-MM-DD && has dateEnd=null - is ok to render in the list as it may be a lifetime promo
3- only show in list if dateStart is today or has already passed
Lets assume this is your list:
List sampleList = [
{"dateStart": "2022-11-18", "dateEnd": "2022-11-22"},
{"dateStart": "2022-11-20", "dateEnd": "2022-11-20"},
{"dateStart": "2022-10-20", "dateEnd": "2022-11-19"},
{"dateStart": "2022-10-20", "dateEnd": null},
];
so you can get your list like this:
var result = sampleList.map((e) {
if (e['dateStart'] != null) {
DateTime startDate =
DateFormat("yyyy-MM-dd").parse(e['dateStart'] + ' 23:59');
DateTime? endDate = e['dateEnd'] != null
? DateFormat("yyyy-MM-dd hh:mm").parse(e['dateEnd'] + ' 23:59')
: null;
var now = DateTime.now();
if ((startDate.isBefore(now) || startDate == now) &&
(endDate == null || endDate.isBefore(now))) {
return e;
}
}
}).toList();
result.removeWhere((element) => element == null);
print("result = $result");//result = [{dateStart: 2022-10-20, dateEnd: 2022-11-19}, {dateStart: 2022-10-20, dateEnd: null}]
now you can use result to show your list.

How can I add working days to a specific date (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)

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');
}

How to add range validation for year in flutter

I've tried to add year range validation it must be between 1850 to the current year. i've tried but it's not working.
Here is the code I've tried
String validateestablishedyear(String value) {
var date = new DateTime.now();
int currentYear = date.year;
int userinputValue = 0;
print('currentYear = $currentYear');
print('input value = $value');
print('value = ${value is int}');
print('value = ${value is String}');
if (value is String && value.length == 0) {
return "Established Year is Required";
} else {
userinputValue = int.parse(value);
}
if (userinputValue < 1850 && userinputValue >= currentYear) {
return "Year must be between 1850 and $currentYear";
}
return null;
}
Just change your code as below,
if (userinputValue < 1850 || userinputValue >= currentYear) {
return "Year must be between 1850 and $currentYear";
}
You're logic is wrong. you should have use || instead of &&