Sunday, October 30, 2011

Find out Number of Days in Month/Year using java

How to find out number of days in a given month and year

Code snippet to find out the numbe rof days in a month.

...
..
/**
 * util method to find the number of day in the given passed month
 * @param month  
 * @return last days of the month
 */
public int getDaysInMonth(Date dt) {

 if (dt == null) dt = new Date();

 Calendar cal = Calendar.getInstance();
 cal.setTime(dt);

 return cal.getActualMaximum(cal.DAY_OF_MONTH);


/**
 * util method to find the last day of the given  year
 * @param month
 * @param year
 * @return last days of the month
 */
public int getDaysInYear(Date dt) {

 if (dt == null) dt = new Date();

 Calendar cal = Calendar.getInstance();
 cal.setTime(dt);

 return cal.getActualMaximum(cal.DAY_OF_YEAR);
}


Main Method to test this


public static void main(String[] args) {
 try {   
   
  System.out.println(" last day os the month..."+ new ReqDXCommonUtil().getDaysInMonth(new Date()));
 } catch (Throwable e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}




No comments:

Post a Comment