There are a million posts on how to get the current day of the week here on Stack, and I've been through all of them to no avail. I'm going through the API to and I'm still not seeing how to do this.
I need to setup a weekly calendar with Java. So if Sunday was the 29th, Monday will be the 30th, Tues the 31st OR 1st, and Wed the 1st or 2nd and so on.
So what I need to do is get the first day of the week (Sunday, which would correspond to 1 in the Calendar._DAY_OF_WEEK
), its day of the month (Which would be Calendar.DAY_OF_MONTH
), and the next six days after that, taking into account the possibility that a new month could start.
I know this sounds simple but I've been scrounging around StackOverflow for hours now and amazingly I haven't found anything like this.
This will get the days of the current week.
private Locale locale = Locale.UK;
// 1. create calendar
private Calendar cal = new GregorianCalendar(locale);
private DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, locale);
public void getThisWeeksDays() {
// 2. set calendar to the current date
cal.setTime(new Date());
cal.setFirstDayOfWeek(Calendar.SUNDAY);
// 3. set calendars dOW field to the first dOW (last sunday)
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
for (int i = 0; i < 7; i++) {
// 4. get some infomation
String nameOfMonth = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locale);
String nameOfDay = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, locale);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(dayOfMonth + ": " + df.format(cal.getTime()));
// 5. increase day field; add() will adjust the month if neccessary
cal.add(Calendar.DAY_OF_WEEK, 1);
}
}
Prints out:
1: Sunday, 1 December 2013
2: Monday, 2 December 2013
3: Tuesday, 3 December 2013
4: Wednesday, 4 December 2013
5: Thursday, 5 December 2013
6: Friday, 6 December 2013
7: Saturday, 7 December 2013