Sidhu
Sidhu

Reputation: 96

Calendar - Dates as per Week - Java

public static void main(String[] args) {
  int week = 1;
  int year = 2010;


  Calendar calendar = Calendar.getInstance();
  calendar.clear();
  calendar.set(Calendar.WEEK_OF_YEAR, week);
  calendar.set(Calendar.YEAR, year);


  Date date = calendar.getTime();
  System.out.println(date);
}

I'm looking for the exact start and end DATE's as per our desktop calendars if I give week, year as input. But the above code is giving the output as 27th Jan, 2009, Sunday. I know it's because the default first day of a week is SUNDAY as per US, but I need as per the desktop calendar 1st Jan, 2010, Friday as starting date of the week

My Requirement : If my input is :

I need :

   1st May, 2015 --> as first day of the week
   2nd May, 2015 --> as last day of the week

If my input is :

I need :

   1st June, 2015 --> as first day of the week
   6th June, 2015 --> as last day of the week

Can anyone help me?

Upvotes: 1

Views: 291

Answers (2)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

I wrote a Swing calendar widget. One method in that widget calculates the first day of the week when a week starts on a user selected day, like Friday.

startOfWeek is an int that takes a Calendar constant, like Calendar.FRIDAY.

DAYS_IN_WEEK is an int constant with the value 7.

/**
 * This method gets the date of the first day of the calendar week. It could
 * be the first day of the month, but more likely, it's a day in the
 * previous month.
 * 
 * @param calendar
 *            - Working <code>Calendar</code> instance that this method can
 *            manipulate to set the first day of the calendar week.
 */
private void getFirstDate(Calendar calendar) {
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) % DAYS_IN_WEEK;
    int amount = 0;
    for (int i = 0; i < DAYS_IN_WEEK; i++) {
        int j = (i + startOfWeek) % DAYS_IN_WEEK;
        if (j == dayOfWeek) {
            break;
        }
        amount--;
    }
    calendar.add(Calendar.DAY_OF_MONTH, amount);
}

The rest of the code can be seen in my article, Swing JCalendar Component.

Upvotes: 1

Alex Pruss
Alex Pruss

Reputation: 534

Instead of using CALENDAR.Week, use Calendar.DAY_OF_YEAR. I just tested it and it works for me:

public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.YEAR, 2010);
    calendar.set(Calendar.DAY_OF_YEAR, 1);
    System.out.println(calendar.getTime());
    calendar.set(Calendar.DAY_OF_YEAR, 7);
    System.out.println(calendar.getTime());
}

If you want this to work for an arbitrary week, just do some math to figure out which day of the year you want.

Edit: If you want to input a month as well, you can use Calendar.DAY_OF_MONTH.

Upvotes: 1

Related Questions