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.
OutputWeek 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.