I need to create 2 buttons, weekly and monthly. When I click these, I need to get the week/month from the current day. If the current date is 5th January, when I click the weekly button, I should only get the date from 1st January to 5th. Cannot exceed to December. (pls excuse if there is any mistake in my English). Can someone please tell me how to implement this in flutter?
static DateTime? getFromDate(int calenderType) {
// calenderType 2 = week
// calenderType 3 = month
// calenderType 4 = year
DateTime lastDayOfMonth = new DateTime(DateTime.now().year, DateTime.now().month, 0);
DateTime lastYear = new DateTime(DateTime.now().year,1,0);
if(calenderType==2){
DateTime weekDate = DateTime.now().subtract(Duration(days: 7));
if(lastDayOfMonth.isBefore(weekDate)){
print('before'+weekDate.toString());
return weekDate;
}
else{
print('after'+weekDate.toString());
return lastDayOfMonth.add(Duration(days: 1));
}
}else if(calenderType == 3){
int totalDays = DateTimeRange(
start: DateTime(DateTime.now().year,DateTime.now().month,1),
end: DateTime(DateTime.now().year,DateTime.now().month + 1))
.duration
.inDays;
DateTime monthDate = DateTime.now().subtract(Duration(days: totalDays));
if(lastDayOfMonth.isBefore(monthDate)){
print('before'+monthDate.toString());
return monthDate;
}
else{
print('after'+monthDate.toString());
return lastDayOfMonth.add(Duration(days: 1));
}
}
else if(calenderType ==4) {
int totalDays = DateTimeRange(start:DateTime(DateTime.now().year,1,1),
end:DateTime(DateTime.now().year,DateTime.now().month,DateTime.now().day)).duration.inDays;
DateTime yearDate = DateTime.now().subtract(Duration(days: totalDays));
if(lastYear.isBefore(yearDate)){
print('before'+yearDate.toString());
return yearDate;
}
else{
print('after'+yearDate.toString());
return lastYear.add(Duration(days: 1));
}
}
This solves it.