Home » Core Java » util » Calendar » Get week of month and year

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments