Compare if two dates are within same week in android

use something like this:

Calendar c = Calendar.getInstance();
Integer year1 = c.get(c.YEAR);
Integer week1 = c.get(c.WEEK_OF_YEAR);

Calendar c = Calendar.getInstance();
c.setTimeInMillis(/*Second date in millis here*/);
Integer year2 = c.get(c.YEAR);
Integer week2 = c.get(c.WEEK_OF_YEAR);

if(year1 == year2) {
    if(week1 == week2) {
         //Do what you want here
    }
}

This should do it :D


Just posting a slightly modified solution based on @FabianCook and as pointed out by @harshal his solution doesn't cater for two dates on different years but in the same week.

The modification is to actually set the DAY_OF_WEEK in both Calendar dates to point to Monday.....in this case both dates will be set to the same day even if they are in different years and then we can compare them.

Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int year1 = cal1.get(Calendar.YEAR);
int week1 = cal1.get(Calendar.WEEK_OF_YEAR);

Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(/*Second date in millis here*/);
cal2.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
int year2 = cal2.get(Calendar.YEAR);
int week2 = cal2.get(Calendar.WEEK_OF_YEAR);

if(year1 == year2 && week1 == week2){
    //Do what you want here
}

You can get the week number for your date using c.get(Calendar.WEEK_OF_YEAR) and compare the results for your two dates.

Also accessing constants via instance variables (c.YEAR) is not recommended - access them using classes (Calendar.YEAR).

Tags:

Java

Date

Android