VOOZH about

URL: https://www.geeksforgeeks.org/java/calculate-the-week-number-of-the-year-for-a-given-date-in-java/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 21 Feb, 2024

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

  • Using LocalDate class(Java 8 and later)
  • Using Calendar class(pre-Java 8)

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.


Output
Week of the year: 5

Explanation of the above Program:

  • First, we have imported java.time.LocalDate, it is used to represent a specific date without its time-zone and java.time.temporal.WeekFields to access the week fields.
  • Now. we define a class named WeekOfTheYear.
  • Inside the main method, we have created a LocalDate object named givenDate representing a particular specified date LocalDate.of().
  • The givenDate.get(WeekFields.ISO.weekOfWeekBasedYear()) returns an integer which represents current date of the year based on ISO-8601 standard.
  • After that, it prints the week.

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

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


Output
Week of the year: 5

Explanation of the above Program:

  • First, we import java.time.LocalDate, it is used to manipulate date and time.
  • Now, we define a class named WeekOfTheYear.
  • Then inside main method, we create an instance of Calendar class using getInstance( ) method.
  • Then we set the date by set( ) method it takes 3 arguments the year, the month and the day of the month.
  • After that we use get( ) method to get the week of the year by passing Calendar.WEEK_OF_YEAR as argument.
  • After that, it prints the week number.
Comment