Reputation: 5954
I would like to get dates for a given week number. For Instance, if I have the week number as 15, I need to get dates: 05-04-2015, 06-04-2015, 07-04-2015, 08-04-2015, 09-04-2015, 10-04-2015, 11-04-2015.
Is this possible? If so, how?
Let me know,
Thanks!
Upvotes: 1
Views: 809
Reputation: 256
Here is my solution:
Calendar c = new GregorianCalendar(Locale.getDefault());
c.set(Calendar.WEEK_OF_YEAR, 15);
c.set(Calendar.YEAR, 2015);
String result = "";
int firstDayOfWeek = c.getFirstDayOfWeek();
for (int i = firstDayOfWeek; i < firstDayOfWeek + 7; i++) {
c.set(Calendar.DAY_OF_WEEK, i);
result += new SimpleDateFormat("yyyy.MM.dd").format(c.getTime()) + "\n";
}
As an input, except for the week, you need to have a year. Pay attention that the first day of week depends on Locale.
Upvotes: 1
Reputation: 1502
int yourYear = 1997;
Calendar c1 = Calendar.getInstance();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
c1.set(yourYear, 1, 1);
c1.add(Calendar.DATE, WEEK*7);
for (int i = 0, i < 7; i++){
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
c1.add(Calendar.DATE, 1);
}
Upvotes: 2
Reputation: 998
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
Upvotes: 1