Alternate Java Calendar Java Calendar with the following function

I need to start my calendar from Monday. As of today (07 / aug / 2012), from day one, like Monday and the minimum days of the week, like 1, java provides me with a weekly week of 33, and Android 32, WHY?

So, I need a calendar alternative that has the following function. The code I'm using is:

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)); 

Any help?

+4
source share
1 answer

TL; DR

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

32

Locale

Not sure about the direct answer to your question, but may have different Locale values ​​in the game. In Calendar definition of the week depends on the locale.

But this is controversial . You should use the java.time classes that replaced the Calendar class.

java.time

Calendar is part of the problematic old time classes, which are now deprecated, are being superseded by java.time classes. For earlier Android, see Recent Bullets below.

You must define what you mean by week number. There are different ways to determine the week and week numbers.

By default, java.time classes use the standard definition of ISO 8601 : week # 1 has the first Thursday of the calendar year, and starts on Monday (as you requested). Thus, years have 52 or 53 weeks. The first and last few days of a calendar year can land in the previous / next weekly year.

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

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

Interrogate the standard week number. You can request any of these TemporalField objects: IsoFields.WEEK_BASED_YEAR and IsoFields.WEEK_OF_WEEK_BASED_YEAR

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

Reset the console using the standard ISO 8601 YYYY-Www-D format .

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

See this code run on IdeOne.com .

2012-08-07 - ISO 8601 Week: 2012-W32-2

By the way, if Android can ever launch the ThreeTen-Extra library, you will find its YearWeek useful.

About java.time

The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , Calendar and SimpleDateFormat .

The Joda-Time project, now in maintenance mode , we recommend switching to the java.time classes.

To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .

Where to get java.time classes?

0
source

All Articles