Java – Android Java calendar replacement with the following features

Android Java calendar replacement with the following features… here is a solution to the problem.

Android Java calendar replacement with the following features

I need to start my calendar on Monday.
According to today’s date (August 7, 2012), the first day is Monday, the minimum number of days of the week is 1, java gives me the 33rd week of the year and android is 32, why?

So I need a calendar replacement with the following features.
The code I’m using:

Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setMinimalDaysInFirstWeek(1);

out("For date : "+df.format(cal.getTime())+" Week = "+cal.get(Calendar.WEEK_OF_YEAR));

Does it help?

Solution

tl; dr

LocalDate.of( 2012 , Month.AUGUST , 7 )
         .get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) 

32

Locale

Not sure of the direct answer to your question, but most likely a different Locale value is at work. In Calendar, the definition of the week varies by region.

But this is moot. You should use the java.time class that replaces the Calendar class.

java.time

Calendar is part of the troublesome old datetime classes that are now left behind, replaced by the java.time class. For earlier Androids, see the last bullet below.

You must define what the week number means. There are different ways to define weeks and week numbers.

By default, the java.time class uses the standard ISO 8601 definition : Week 1 is the first Thursday of the calendar year, starting on Monday (as you requested). So the year has 52 or 53 weeks. The first and last days of the calendar year may fall on the pre/after year based on the week.

The LocalDate class represents a pure date value without time and time zone.

LocalDate ld = LocalDate.of( 2012 , Month.AUGUST , 7 ) ;

Query the standard week number. You can ask any one of TemporalField Object: IsoFields.WEEK_BASED_ YEAR & IsoFields.WEEK_OF_WEEK_BASED_YEAR

int weekOfWeekBasedYear = ld.get( IsoFields.WEEK_OF_WEEK_BASED_YEAR ) ;
int yearOfWeekBasedYear = ld.get( IsoFields.WEEK_BASED_YEAR ) ;

Use standard dumps to the console ISO 8601 format of YYYY-Www-D

String isoOutput = yearOfWeekBasedYear + "-W" + String.format("%02d", weekOfWeekBasedYear) + "-" + dayOfWeekNumber  ;
System.out.println( ld + " is ISO 8601 week: " + isoOutput ) ;

Check out this code run live at IdeOne.com

2012-08-07 is ISO 8601 week: 2012-W32-2

By the way, if Android can run ThreeTen-Extra library, you’ll find it YearWeek class is useful.


About java.time

within the java.time framework in Java 8 and later. These classes replace the troublesome old classes legacy datetime classes, eg java.util.Date , Calendar , & SimpleDateFormat .

Joda-Time project, now in maintenance mode, it is recommended to migrate to java.time class.

To learn more, see Oracle Tutorial. The specification is JSR 310

Where do I get the java.time class?

Related Problems and Solutions