Home > Enterprise >  How to find week of a year for a given date for a given start of week other than Monday?
How to find week of a year for a given date for a given start of week other than Monday?

Time:09-29

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?

CodePudding user response:

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 )
.get(
    WeekFields
    .of( DayOfWeek.FRIDAY , 4 )
    .weekOfYear()                    // Returns a `TemporalField` object.
)

CodePudding user response:

// Here is a solution that worked for me. Let me know if it helps or not. Thanks 

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 :-
// SUNADY 3
// MONDAY 4
// TUESDAY 5
// WEDNESDAY 6
// THURSDAY 7
// FRIDAY 1
// SATURDAY 2
  • Related