Java Day of Week getDayAfterGivenDate(Date date, int dayOfWeek)

Here you can find the source of getDayAfterGivenDate(Date date, int dayOfWeek)

Description

Find the given day of the week (sunday, monday etc.) that falls before the given date

License

Open Source License

Parameter

Parameter Description
date The date after which the date we compute should fall
dayOfWeek The day of week on which the date we compute should fall (Use Calendar.SUNDAY etc.)

Declaration

public static Date getDayAfterGivenDate(Date date, int dayOfWeek) 

Method Source Code

//package com.java2s;
// distribute, sublicense, and/or sell copies of the Software, and to

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

public class Main {
    /**/*from   w w  w  .  j av  a 2 s .c  o m*/
     * Find the given day of the week (sunday, monday etc.) that falls before
     * the given date
     * 
     * @param date
     *            The date after which the date we compute should fall
     * @param dayOfWeek
     *            The day of week on which the date we compute should fall (Use
     *            Calendar.SUNDAY etc.)
     * @return
     */
    public static Date getDayAfterGivenDate(Date date, int dayOfWeek) {
        // First find what day of week the given date falls
        Calendar cal = Calendar.getInstance();

        cal.setTime(date);

        int originalDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

        int dayDiff = dayOfWeek - originalDayOfWeek;

        if (dayDiff <= 0) {
            dayDiff += 7;
        }

        cal.add(Calendar.DATE, dayDiff);

        return cal.getTime();
    }
}

Related

  1. getDateOfWeek(int week)
  2. getDateOfWeek(int year, int weekOfYear, int i)
  3. getDateOfYearWeek(int yearNum, int weekNum, int dayOfWeek)
  4. getDateWeek(String date)
  5. getDay(long date, int startOfWeek, int increment)
  6. getDayOfWeek()
  7. getDayOfWeek(Date date)
  8. getDayOfWeek(int _year, int _month, int _day)
  9. getDayOfWeek(int year, int month, int day)