How to Find Which Week of the Year, Month in Java



The Calendar class in Java provides methods to determine the week of the year and the week of the month. Using fields like WEEK_OF_YEAR and WEEK_OF_MONTH, you can easily find this information based on the current date.

Finding week of the year and month

The Java Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. Following are the important points about Calendar

  • This class also provides additional fields and methods for implementing a concrete calendar system outside the package.

  • Calendar defines the range of values returned by certain calendar fields.

The Calendar object (cl) is set to the current date using the setTime(d1) method. The WEEK_OF_YEAR and WEEK_OF_MONTH fields are then used to extract the week numbers for the year and month.

Example

The following example displays week no of the year & month

import java.util.*;

public class Main {
   public static void main(String[] args) throws Exception {
      Date d1 = new Date();
      Calendar cl = Calendar. getInstance();
      cl.setTime(d1);
      
      System.out.println("today is " + cl.WEEK_OF_YEAR+ "week of the year");
      System.out.println("today is a "+cl.DAY_OF_MONTH + "month of the year");
      System.out.println("today is a "+cl.WEEK_OF_MONTH +"week of the month");
   }
}

Output

today is 30 week of the year
today is a 5month of the year
today is a 4week of the month

Finding current week and adding one week to the month

The Calendar instance (cal) is used to determine the current week of the month and year. The method add(Calendar.WEEK_OF_MONTH, 1) is used to add one week to the current date. The final output shows the date after one week is added, as well as the corresponding week of the year and month.

Example

The following program uses SimpleDateFormat to format the month

import java.util.Calendar;
 
public class GetWeekOfMonthAndYear {
   public static void main(String[] args) {
      Calendar cal = Calendar.getInstance();
      System.out.println("Current week of month is : " +cal.get(Calendar.WEEK_OF_MONTH));
      System.out.println("Current week of year is : " +cal.get(Calendar.WEEK_OF_YEAR));
      cal.add(Calendar.WEEK_OF_MONTH, 1);
      System.out.println(
         "date after one year : " + (cal.get(Calendar.MONTH) + 1)+ "-"+ cal.get(Calendar.DATE)+ "-"+ cal.get(Calendar.YEAR)); 
   }
}

Output

Current week of month is : 2
Current week of year is : 46
date after one year : 11-18-2016
java_date_time.htm
Advertisements