Skip to main content

APIzation: Replication Package

[Q#2109145][A#2109186] How to get first day of a given week number in Java

https://stackoverflow.com/q/2109145

Let me explain myself. By knowing the week number and the year of a date: But now I don't know how to get the date of the first day of that week. I've been looking in Calendar, Date, DateFormat but nothing that may be useful… Any suggestion? (working in Java)

Answer

https://stackoverflow.com/a/2109186

Those fields does not return the values. Those are constants which identifies the fields in the Calendar object which you can get/set/add. To achieve what you want, you first need to get a Calendar, clear it and set the known values. It will automatically set the date to first day of that week. Please learn to read the javadocs to learn how to use classes/methods/fields and do not try to poke random in your IDE ;) That said, the java.util.Date and java.util.Calendar are epic failures. If you can, consider switching to Joda Time.

APIzation

// We know week number and year.
int week = 3;
int year = 2010;

// Get calendar, clear it and set week number and year.
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);

// Now get the first day of week.
Date date = calendar.getTime();
package com.stackoverflow.api;

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

public class Human2109186 {

  public static Date getFirstDayOfWeek(int week, int year) {
    // Get calendar, clear it and set week number and year.
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.WEEK_OF_YEAR, week);
    calendar.set(Calendar.YEAR, year);

    // Now get the first day of week.
    return calendar.getTime();
  }
}

package com.stackoverflow.api;

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

/**
 * How to get first day of a given week number in Java
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/2109186">https://stackoverflow.com/a/2109186</a>
 */
public class APIzator2109186 {

  public static Date getDay(int week, int year) throws Exception {
    // Get calendar, clear it and set week number and year.
    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.WEEK_OF_YEAR, week);
    calendar.set(Calendar.YEAR, year);
    return calendar.getTime();
  }
}