Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Getting weekends date in Java

    • 0
    • 4
    • 1
    • 4
    • 0
    • 0
    • 0
    • 0
    • 4.07k
    Comment on it

    To get weekend list for a current year, write the following code:

    private ArrayList weekendList = null;
    public void findWeekendsList()
    {
        weekendList = new ArrayList();
        Calendar calendar = null;
        calendar = Calendar.getInstance();
        // The while loop ensures that you are only checking dates in the current year
        while(calendar.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR)){
            // The switch checks the day of the week for Saturdays and Sundays
            switch(calendar.get(Calendar.DAY_OF_WEEK)){
            case Calendar.SATURDAY:
            case Calendar.SUNDAY:
                weekendList.add(calendar.getTime());
                break;
            }
            // Increment the day of the year for the next iteration of the while loop
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
    }
    

    If you want to check dates in the specified year, then set the date as bellow:

    calendar.setTime(dateStr); // Where dateStr is the specified date after which you want to find weekends.
    

    then use the same code as defined above.

    You can also find the nearest weekend of current date by writing below code:

    private Date getNearestWeekend()
    {
        try {
            Calendar c = Calendar.getInstance();
            c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date weekendDate = sdf.parse(sdf.format(c.getTime()));
            return weekendDate;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    
    }
    

    Also from below code you can find nearest weekend of specified date:

    Calendar cal = Calendar.getInstance();
    cal.setTime(userCategoryLikes.getCreatedTime());// Here you will pass the date for which you want to get weekend.
    cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date weekendDate = sdf.parse(sdf.format(cal.getTime()));
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: