Calendar

Get week of month and year

With this example we are going to demonstrate how to get the week of month and year from a Calendar object. The 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. It also provides methods for manipulating the calendar fields, such as getting the date of the next week. In short, to get the week of month and year from a Calendar object you should:

  • Create a new Calendar object, using getInstance() API method of Calendar, that gets a calendar using the default time zone and locale.
  • Use get(int field) API method of Calendar, setting the field to Calendar.WEEK_OF_MONTH, to get the week of month.
  • Use get(int field) API method of Calendar again, setting the field to Calendar.WEEK_OF_YEAR this time, to get the week of year.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.Calendar;
 
public class GetWeekOfMonthAndYear {
 
  public static void main(String[] args) {
 
    //Create calendar instance
    Calendar calendar = Calendar.getInstance();
   
    System.out.println("Current week of this month = " + calendar.get(Calendar.WEEK_OF_MONTH));


   
    System.out.println("Current week of this year = " + calendar.get(Calendar.WEEK_OF_YEAR));
   
  }
}

Output:

Current week of this month = 3
Current week of this year = 29

 
This was an example of how to get the week of month and year from a Calendar object in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button