java left logo
java middle logo
java right logo
 

Home arrow Java SE Tips
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4100
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
Get the number of days in a month E-mail
User Rating: / 45
PoorBest 

This tip shows the ways to obtain the number of days in a month.

public static int daysInMonth(GregorianCalendar c) {
  int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
  daysInMonths[1+= c.isLeapYear(c.get(GregorianCalendar.YEAR)) 0;
  return daysInMonths[c.get(GregorianCalendar.MONTH)];
}

Actually, the Calendar class provides a method to that very simply. For a given Calendar or GregorianCalendar object:

   calObject.getActualMaximum(calobject.DAY_OF_MONTH) 

In the Java API documentation there is a note saying that The version (getActualMaximum()) of this function on Calendar uses an iterative algorithm to determine the actual maximum value for the field. There is almost always a more efficient way to accomplish this (in most cases, you can simply return getMaximum()). GregorianCalendar overrides this function with a more efficient implementation. So it looks like it's a lot more efficient to call getActualMaximum from a GregorianCalendar object than a Calendar object.

   gregCalObject.getActualMaximum(gregCalObject.DAY_OF_MONTH) 

 Related Tips

 
< Prev   Next >
 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.