For example: given month = 2, and given Year = 2014, i got the list of weeks using this following code. why i applied 1 for month is defaultly the month was start with index only.
SampleCode:
Calendar calendar = Calendar.getInstance();
calendar.set(1, 2014);
calendar.set(2014, 1, 1);
int ndays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Set<Integer> weeks = new HashSet<Integer>();
for (int i = 1; i <= ndays; i++) {
weeks.add(calendar.get(Calendar.WEEK_OF_YEAR));
calendar.add(Calendar.DATE, 1);
}
Result: weeks => [8, 9, 5, 6, 7]
After getting this result how can i get what are the dates are available with in the weekofyear. 2014 Febraury month, 5 th week having only one day (saturday). remaining weeks having sevendays except last 9th week.
I Expected Format:
week5 => 1-saturday
week6 => 2-sunday
3-monday
4-tuesday
5-wednesday
6-thursday
7-friday
8-saturday
week7 => 9-sunday
.
.
.
.
week9 => 23-sunday
24-monday
25-tuesday
26-wednesday
27-thursday
28-friday
29-saturday
some one guide me to get this List< Key,datelist > pair like above result.
why do you want to collect at first the weeks, and then find the days of the week. As you are already looping over all days of a month, you could just create a map, which has the week as key and the list of days as value.
Somehow like that:
Calendar calendar = Calendar.getInstance();
calendar.set(1, 2014);
calendar.set(2014, 1, 1);
int ndays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Map<Integer, List<Integer>> map = new TreeMap<Integer, List<Integer>>();
for (int i = 1; i <= ndays; i++) {
int week = calendar.get(Calendar.WEEK_OF_YEAR);
int day = calendar.get(Calendar.DAY_OF_MONTH);
List<Integer> dayList = map.get(week);
if (dayList == null) {
dayList = new ArrayList<Integer>();
map.put(week, dayList);
}
dayList.add(day);
calendar.add(Calendar.DATE, 1);
}
//Check the result:
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
System.out.println("Week: " + entry.getKey());
for (int day : entry.getValue()) {
System.out.println("Day: " + day);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.