Reputation: 11
Suppose I set week start day as "Friday" in Java calendar variable .I need to find week number of the year similar to ISO week. Is there any simple way to find the week number?
Upvotes: 0
Views: 1470
Reputation: 11
Since you tagged your question [groovy], here is a Groovy solution that worked for me. Let me know if it helps or not.
import static java.util.Calendar.*
Calendar calendar = Calendar.getInstance();
calendar.setMinimalDaysInFirstWeek(6);
calendar.setFirstDayOfWeek(Calendar.WEDNESDAY);
date=Date.parse("yyyy-MM-dd","2022-01-05")
/* Set Your date whose week number is needed*/
calendar.setTime(date);
/* Get Similar to ISO8601 week number */
print calendar.get(Calendar.WEEK_OF_YEAR); // Prints 1
// All you need to set deviation as per your need, one solution can be by setting setMinimalDaysInFirstWeek as :-
// SUNDAY 3
// MONDAY 4
// TUESDAY 5
// WEDNESDAY 6
// THURSDAY 7
// FRIDAY 1
// SATURDAY 2
Upvotes: -1
Reputation: 339332
Since you want something other than a standard ISO 8601 week, you must specify your definition of week.
For a java.time.LocalDate
object, pass to its get
method a TemporalField
obtained from a WeekFields
object. 👉 You will need to specify which day-of-week you consider to be first, and specify the minimum of days in a first week of year. After that, you get back an int
for week-of-year.
Ironically, easier done than said. Read on.
java.time.temporal.WeekFields
The terrible Calendar
& GregorianCalendar
classes were years ago supplanted by the modern java.time classes defined in JSR 310.
As commented by Ole V.V., you can use WeekFields
class for your purpose. Use LocalDate
to represent a date value (year, month, and day-of-month). Call WeekFields.of( DayOfWeek firstDayOfWeek , int minimalDaysInFirstWeek )
.
LocalDate
.of( 2022 , Month.SEPTEMBER , 28 ) // Returns a `LocalDate` object.
.get(
WeekFields
.of( DayOfWeek.FRIDAY , 4 ) // Returns a `WeekFields` object.
.weekOfYear() // Returns a `TemporalField` object.
) // Returns an `int` integer number, the week-of-year.
See this code run at IdeOne.com.
weekOfYear: 39
By the way, for those readers who are using a standard ISO 8601 week, I recommend adding the ThreeTen-Extra library to your project, for its YearWeek
class.
Upvotes: 2