views:

1302

answers:

3

Let me explain myself. By knowing the week number and the year of a date:

Date curr = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(curr);
int nweek = cal.WEEK_OF_YEAR;
int year = cal.YEAR;

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)

+9  A: 

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.

// 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();

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.

BalusC
Note that week numbers are locale dependent. Be _absolutely certain_ that your locale is correct!
Thorbjørn Ravn Andersen
currently using Joda time, so much easier to work with, I would recommend switching to it
Craig Angus
Thank you, that's exactly what I needed. Anyway I'm going to take a look to Joda Time as you suggested. I'm still in the beginner level, still have to learn a lot.
framara
A: 

I haven't done much Date stuff in java but a solution might be:

cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_WEEK));

Logic:

Get the day of the week and substract it from the current date (might need -1, depending on wether you need monday to be first day of the week or sunday)

dbemerlin
A: 

Here's some quick and dirty code to do this. This code creates a calendar object with the date of the current day, calculates the current day of the week, and subtracts the day of the week so you're on the first one (Sunday). Although I'm using DAY_OF_YEAR it goes across years fine (on 1/2/10 it'll return 12/27/09 which is right).

import java.text.Format; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;

public class DOW {

public static void main(String[] args) {
    DOW dow = new DOW();
    dow.doIt();
    System.exit(0);
}

private void doIt() {
    Date curr = new Date(); 
    Calendar cal = Calendar.getInstance(); 
    cal.setTime(curr); 
    int currentDOW = cal.get(Calendar.DAY_OF_WEEK);
    cal.add(Calendar.DAY_OF_YEAR, (currentDOW * -1)+1);

    Format formatter = new SimpleDateFormat("MM/dd/yy");
    System.out.println("First day of week="+formatter.format(cal.getTime()));
}

}

SOA Nerd