• Register
Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

How to check a day is in the current week in Java

0 votes
10 views
How to check a day is in the current week in Java?
asked Mar 1 in Java by Nikhil Kumar

1 Answer

0 votes
package com;

import java.util.Calendar;
import java.util.Date;

public class CurrentWeek {

    public static void main(String[] args) {        
        Date currentDate = new Date();
        boolean isDateExists = isDateInCurrentWeek(currentDate);
        System.out.println("Date Exists: " + isDateExists);
        
        long ltime=currentDate.getTime()+8*24*60*60*1000; // add 8 days
        isDateExists = isDateInCurrentWeek(new Date(ltime));
        System.out.println("Date Exists: " + isDateExists);
        
        ltime=currentDate.getTime()+3*24*60*60*1000; // add 8 days
        isDateExists = isDateInCurrentWeek(new Date(ltime));
        System.out.println("Date Exists: " + isDateExists);
    }
   
    public static boolean isDateInCurrentWeek(Date date) {
        Date currentWeekStart, currentWeekEnd;

        Calendar currentCalendar = Calendar.getInstance();
        currentCalendar.setFirstDayOfWeek(Calendar.MONDAY);
        while(currentCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY){
            currentCalendar.add(Calendar.DATE,-1);//go one day before
        }
        currentWeekStart = currentCalendar.getTime();

        currentCalendar.add(Calendar.DATE, 6); //add 6 days after Monday
        currentWeekEnd = currentCalendar.getTime();

        Calendar targetCalendar = Calendar.getInstance();
        targetCalendar.setFirstDayOfWeek(Calendar.MONDAY);
        targetCalendar.setTime(date);


        Calendar tempCal = Calendar.getInstance();
        tempCal.setTime(currentWeekStart);

        boolean result = false;
        while(!(tempCal.getTime().after(currentWeekEnd))){
            if(tempCal.get(Calendar.DAY_OF_YEAR)==targetCalendar.get(Calendar.DAY_OF_YEAR)){
                result=true;
                break;
            }
            tempCal.add(Calendar.DATE,1);//advance date by 1
        }
        return result;
    }
}
Output:-
Date Exists: true
Date Exists: false
Date Exists: true
answered Mar 1 by ranju_12 (1,740 points)
...