In the below code, I want to compare a start date and an end date with my schedule date. I want to find within a week how many tasks are availables.
Suppose 16-03-2020 is the start date and 22-03-2020 the end date, my schedule date are like this 16 to 20. How many dates are there want to
calendar = Calendar.getInstance();
Log.v("Current Week", String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR)));
int current_week = calendar.get(Calendar.WEEK_OF_YEAR);
int week_start_day = calendar.getFirstDayOfWeek(); // this will get the starting day os week in integer format i-e 1 if monday
Toast.makeText(getContext(), "Current Week is" + current_week + "Start Day is" + week_start_day, Toast.LENGTH_SHORT)
.show();
// get the starting and ending date
// Set the calendar to sunday of the current week
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Print dates of the current week starting on Sunday
DateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
endDate = df.format(calendar.getTime());
System.out.println("Start Date = " + startDate);
System.out.println("End Date = " + endDate);
if (startDate.compareTo(scheduleDate) < 0 && endDate.compareTo(scheduleDate) > 0) {
listTask.add(taskModel);
taskAdapter.notifyDataSetChanged();
}
else if (name.equals("date_start")) {
scheduleDates = String.valueOf(values);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
// String inputDateStr="2013-06-24";
Date date = null;
try {
date = inputFormat.parse(scheduleDates);
scheduleDate = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
Convert your date into timestamp instead of string.
Then it is just a comparison between integers.
// set starting and ending date
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
long startDate = calendar.getTime().getTime();
calendar.add(Calendar.DATE, 6);
long endDate = calendar.getTime().getTime();
Log.d(TAG,"Start Date = " + startDate);
Log.d(TAG,"End Date = " + endDate);
long scheduleDate = Calendar.getInstance().getTime().getTime();
if (startDate <= scheduleDate && endDate > scheduleDate) {
listTask.add(taskModel);
taskAdapter.notifyDataSetChanged();
}
Or you can use the Date comparison methods
// set starting and ending date
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date startDate = calendar.getTime();
calendar.add(Calendar.DATE, 6);
Date endDate = calendar.getTime();
Log.d(TAG,"Start Date = " + startDate);
Log.d(TAG,"End Date = " + endDate);
Date scheduleDate = Calendar.getInstance().getTime();
if (startDate.before(scheduleDate) && endDate.after(scheduleDate)) {
listTask.add(taskModel);
taskAdapter.notifyDataSetChanged();
}