How to detect if a date is within this or next week in java?

前端 未结 5 2058
半阙折子戏
半阙折子戏 2021-02-15 02:05

If I have a date of an event, such as 2011-01-03, how to detect if it is within this or next week in java ? Any sample code ?

Edit :

I thought it was a simple qu

5条回答
  •  别那么骄傲
    2021-02-15 02:39

    for those that has to stick to JDK 7 and can't use joda.time, I wrote this method and tested.

    public static boolean inSameWeek(Date date1, Date date2) {
        if (null == date1 || null == date2) {
            return false;
        }
    
        Calendar earlier = Calendar.getInstance();
        Calendar later = Calendar.getInstance();
    
        if (date1.before(date2)) {
            earlier.setTime(date1);
            later.setTime(date2);
        } else {
            earlier.setTime(date2);
            later.setTime(date1);
        }
        if (inSameYear(date1, date2)) {
            int week1 = earlier.get(Calendar.WEEK_OF_YEAR);
            int week2 = later.get(Calendar.WEEK_OF_YEAR);
            if (week1 == week2) {
                return true;
            }
        } else {
            int dayOfWeek = earlier.get(Calendar.DAY_OF_WEEK); 
            earlier.add(Calendar.DATE, 7 - dayOfWeek);
            if (inSameYear(earlier.getTime(), later.getTime())) {
                int week1 = earlier.get(Calendar.WEEK_OF_YEAR);
                int week2 = later.get(Calendar.WEEK_OF_YEAR);
                if (week1 == week2) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public static boolean inSameYear(Date date1, Date date2) {
        if (null == date1 || null == date2) {
            return false;
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        int year1 = cal1.get(Calendar.YEAR);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 == year2)
            return true;
    
        return false;
    }
    

提交回复
热议问题