Prince Charming
Prince Charming

Reputation: 401

java week count for previous month

In java how can one get number of weeks of previous month, week starting from Monday

cal.setFirstDayOfWeek(Calendar.MONDAY);

cal is Calendar instance

It returns 0 if first day of week is other than Monday. So it has to be counted as previous months last week, that's my requirement.

Upvotes: 0

Views: 677

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 338266

java.time

Avoid using the troublesome old date-time classes now supplanted by the java.time classes.

If your Calendar is actually a GregorianCalendar then convert to a ZonedDateTime.

GregorianCalendar gc = (GregorianCalendar) myCal;
ZonedDateTime zdt = gc.toZonedDateTime();

Extract the date-only.

LocalDate ld = zdt.toLocalDate();

1st to 1st

Get first of this month, and first of next month. Use a TemporalAdjuster defined in TemporalAdjusters (note the plural).

LocalDate firstOfThisMonth = ld.with( TemporalAdjusters.firstDayOfMonth() );
    LocalDate firstOfNextMonth = ld.with( TemporalAdjusters.firstDayOfNextMonth() );

Calculate weeks between.

long weeks = ChronoUnit.WEEKS.between( firstOfThisMonth , firstOfNextMonth );

Monday-to-Monday

If you want Monday-to-Monday, used different TemporalAdjuster already defined in TemporalAdjusters with a DayOfWeek enum object.

LocalDate firstMondayOfThisMonth = ld.with( TemporalAdjusters.firstInMonth( DayOfWeek.MONDAY ) );
LocalDate firstMondayOfNextMonth = ld.plusMonths( 1 ).with( TemporalAdjusters.firstInMonth( DayOfWeek.MONDAY ) );

long weeks = ChronoUnit.WEEKS.between( firstMondayOfThisMonth , firstMondayOfNextMonth );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 0

Korgen
Korgen

Reputation: 5399

Quick and dirty (given the requirements as asked in my comment above):

public static void main(String[] args) {       

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -1);
    cal.set(Calendar.DAY_OF_MONTH,1);
    while ( cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY ) {
        cal.add(Calendar.DAY_OF_WEEK, 1);
    }
    int startingMonth = cal.get(Calendar.MONTH);
    int numberOfWeeks = 0;

    while (cal.get(Calendar.MONTH) == startingMonth ) {          
        cal.add(Calendar.WEEK_OF_MONTH, 1);            
        numberOfWeeks++;                        
    }
    System.out.println("weeks in last month:" + numberOfWeeks);
}

Upvotes: 0

gore_obsessed
gore_obsessed

Reputation: 146

If you want to count all the Mondays in the previous month here you are:

public int getNofWeeks() {
    Calendar cal = Calendar.getInstance();        
    while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        cal.roll(Calendar.DATE, false);
    }        
    int currentMonth = cal.get(Calendar.MONTH);
    int previousMonth = (currentMonth + 12 - 1) % 12;
    int prePreviousMonth = (currentMonth + 12 - 2) % 12;
    int nofWeeks = 0;        
    do {
        int month = cal.get(Calendar.MONTH);
        if (month == previousMonth) {
            nofWeeks++;
        }
        if (month == prePreviousMonth) {
            break;
        }
        cal.roll(Calendar.WEEK_OF_YEAR, false);            
    } while (true);        
    return nofWeeks;
}

Upvotes: 0

anubhava
anubhava

Reputation: 784958

Your question is not very clear but probably you're looking for something like this:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date()); // today's date
// previous month from today
cal.add(Calendar.MONTH, -1);
// get to the 1st week
cal.add(Calendar.DATE, -7 * (cal.get(Calendar.DAY_OF_MONTH)/7));
// Get to the 1st Mon of last month
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// # of days in last month
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
// print # of week since Mon of last month
int numWeeks = ((maxDay-cal.get(Calendar.DATE))/7)+1;
System.out.printf("# of weeks from Mon in last month: %d%n", numWeeks);

Upvotes: 1

Related Questions