Friday, November 19, 2010

Java Code: How to find out the weeknumber in a month to which a given date belong to?

The below code will provide the week number in the format "Week -" + Weeknumber.

    public static String getWeekForDate(Date currentDate) {
        String weekNumber = "";
        ArrayList<Date> weeksList = new ArrayList<Date>();
        int dateCounter = 1;
        int month = currentDate.getMonth();
        Date week1Start = new Date(currentDate.getYear(), month, dateCounter);
        weeksList.add(week1Start);
        Date nextWeekStart = null;
        boolean cont = true;
        while (cont) {
            dateCounter++;
            Date nextDay = new Date(currentDate.getYear(), currentDate
                    .getMonth(), dateCounter);
            if (0 == nextDay.getDay()) {
                nextWeekStart = new Date(currentDate.getYear(), currentDate
                        .getMonth(), dateCounter);
                int tempMonth = nextWeekStart.getMonth();
                if (tempMonth != month) {
                    Date monthEnd = new Date(currentDate.getYear(), currentDate
                            .getMonth() + 1, 1);
                    weeksList.add(monthEnd);
                    cont = false;
                } else {
                    weeksList.add(nextWeekStart);
                }
            }
        }
        for (int index = 0; index < weeksList.size() - 1; index++) {
            if (currentDate.getTime() >= ((Date) weeksList.get(index))
                    .getTime()
                    && currentDate.getTime() < ((Date) weeksList.get(index + 1))
                            .getTime())
                weekNumber = "Week " + (index + 1);
        }
        return weekNumber;
    }

Hope this helps

No comments:

Post a Comment