Open In App

How to Calculate the Week Number of the Year for a Given Date in Java?

In Java, we have the Calendar class and the newer LocalDate class from java.time package. We can use these classes to find which week number of the year for a given date. The java.time package offers better functionality than the older date and time classes such as Calendar class.

In this article, we will learn how to calculate the week number of the year for a given date in Java.



Approaches to Calculate the Week Number of the Year for a Given Date in Java

Program to Calculate the Week Number of the Year for a Given Date in Java

Below is the code implementation of the above two methods with explanations.

Approach 1: Using LocalDate class (Java 8 and later)

Local Date is a newer class introduced in Java 8 which we can use to calculate week numbers. WeekFields.ISO represents the ISO-8601 standard for weeks. We can create a LocalDate instance using the of() method. It enables us to provide custom dates and times.






// Java program to find which week of the year using
// LocalDate class
import java.time.LocalDate;
import java.time.temporal.WeekFields;
  
// Driver Class
public class WeekOfTheYear {
      // Main Function
    public static void main(String[] args)
    {
        // set date //year month day order
        LocalDate givenDate = LocalDate.of(2024, 2, 2);
        
        // get week number
        int weekNumber = givenDate.get(WeekFields.ISO.weekOfWeekBasedYear());
          
          System.out.println("Week of the year: " + weekNumber);
    }
}

Output
Week of the year: 5

Explanation of the above Program:

Approach 2: Using Calendar Class (Pre-Java 8)

In calendar class, we have used set() method to set a given date.




// Java program to find which week of the year
// Using Calendar class
import java.util.Calendar;
  
// Driver Class
public class WeekOfTheYear {
    // Main Function
    public static void main(String[] args)
    {
        // create instance of Calendar class
        Calendar instance = Calendar.getInstance();
  
        // set the date
        instance.set(2024, Calendar.FEBRUARY, 2);
  
        // get the week of the year
        int weekNumber = instance.get(Calendar.WEEK_OF_YEAR);
        System.out.println("Week of the year: " + weekNumber);
    }
}

Output
Week of the year: 5

Explanation of the above Program:


Article Tags :