Sunday, 22 July 2012

Add or subtract weeks to current date using Java Calendar

The java.util.Calendar allows us to do a date arithmetic function such as add or subtract a unit of time to the specified date field.


The method that done this process is the Calendar.add(int field, int amount). Where the value of the field can be Calendar.WEEK_OF_YEAR.So this mean if you want to add/subtract in weeks, use Calendar.WEEK_OF_YEAR .


The complete source code is given below:



import java.util.Calendar;

public class AddWeeksToCurrentWeek {

 public static void main(String[] args) {

  Calendar cal = Calendar.getInstance();

  System.out.println("Today : " + cal.getTime());

  System.out.println("Week_of_Month: " + cal.get(Calendar.WEEK_OF_MONTH));
  System.out.println("Week_of_Year: " + cal.get(Calendar.WEEK_OF_YEAR));

  cal.add(Calendar.WEEK_OF_YEAR, 2);

  System.out.println("2 weeks after : " + cal.getTime());

  System.out.println("2 weeks after- Week_of_Month: "
    + cal.get(Calendar.WEEK_OF_MONTH));

  System.out.println("2 weeks after- Week_of_Year: "
    + cal.get(Calendar.WEEK_OF_YEAR));

  cal.add(Calendar.WEEK_OF_YEAR, -1);

  System.out.println("1 week before : " + cal.getTime());

  System.out.println("1 week before- Week_of_Month: "
    + cal.get(Calendar.WEEK_OF_MONTH));

  System.out.println("1 week before- Week_of_Year: "
    + cal.get(Calendar.WEEK_OF_YEAR));

 }

}
The output is


Today : Mon Jul 23 10:52:05 IST 2012
Week_of_Month: 4
Week_of_Year: 30
2 weeks after : Mon Aug 06 10:52:05 IST 2012
2 weeks after- Week_of_Month: 2
2 weeks after- Week_of_Year: 32
1 week before : Mon Jul 30 10:52:05 IST 2012
1 week before- Week_of_Month: 5
1 week before- Week_of_Year: 31


No comments:

Post a Comment