Nick
Nick

Reputation: 59

Java Fiscal Year Week Counter

I've been all up night trying to figure this out, but nothing I try seems to work. Let say the Fiscal year starts on 10/01 of every year, for example the fiscal year started on 10/01/2012 making this week number 30. I can't seem to find the code that returns the appropriate week number.

The closest I've gotten is this code below which returns week number 16 starting from Jan.

public String getCurrentWeek() {
        GregorianCalendar current = new GregorianCalendar(getCalendar().get(Calendar.YEAR),
            getCalendar().get(Calendar.MONTH), getCalendar().get(Calendar.DATE));

        return Integer.toString(current.get(Calendar.WEEK_OF_YEAR));
    }

Upvotes: 1

Views: 3746

Answers (1)

Tom Anderson
Tom Anderson

Reputation: 47163

I believe:

private static final int LENGTH_OF_WEEK = 7 * 24 * 60 * 60 * 1000;

public static int weekOf(Calendar yearStart, Calendar date) {
    long millisElapsed = date.getTimeInMillis() - yearStart.getTimeInMillis();
    int weeksElapsed = (int) (millisElapsed / LENGTH_OF_WEEK);
    return weeksElapsed + 1;
}

Should do it.

Upvotes: 4

Related Questions