How to get the number of days in a given month with Jodatime?

30 days hath September, April, June and November, All the rest have 31, Excepting February alone (And that has 28 days clear, With 29 in each leap year). 

Can I get this information anagram? (I do not mean the poem, of course)

+46
java datetime jodatime
Sep 22 '10 at 19:35
source share
4 answers

If you have a DateTime object that represents the value in the month, then this is pretty simple. You get the dayOfMonth property from this DateTime object and get the maximum value of the property. Here is an example function:

 public static int daysOfMonth(int year, int month) { DateTime dateTime = new DateTime(year, month, 14, 12, 0, 0, 000); return dateTime.dayOfMonth().getMaximumValue(); } 
+84
Sep 22 '10 at 19:51
source share

Yes, although it is not as beautiful as it could be:

 import org.joda.time.*; import org.joda.time.chrono.*; import org.joda.time.field.*; public class Test { public static void main(String[] args) { GregorianChronology calendar = GregorianChronology.getInstance(); DateTimeField field = calendar.dayOfMonth(); for (int i = 1; i < 12; i++) { LocalDate date = new LocalDate(2010, i, 1, calendar); System.out.println(field.getMaximumValue(date)); } } } 

Please note that I hard-coded the assumption that there are 12 months, and we are interested in 2010. I clearly chose the Gregorian chronology, although - in other chronologies you would have received different answers, of course, (And the "12 months" cycle will not be a valid assumption either ...)

I went for LocalDate , not DateTime , to get the value, to emphasize (albeit weakly) that this value does not depend on the time zone.

It is still not as easy as it seems to think. I do not know what will happen if you use one chronology to build LocalDate , but set the maximum field value in another chronology. I have some ideas on what might happen knowing a certain amount about Joda's time, but this is probably not a good idea :)

+3
Sep 22 '10 at 19:52
source share
 Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, yourMonth); cal.set(Calendar.YEAR, yourYear); cal.getActualMaximum(Calendar.DAY_OF_MONTH); // <-- the result! 
0
Sep 22 '10 at 19:42
source share

Here is another simple function:

 int daysOfMonth(DateTime dt) { int month = dt.getMonthOfYear(); int month2 = month; int days = dt.getDay(); DateTime dt2 = dt; while (month == month2 ) { days++; dt2.addDays(1); month2 = dt2.getMonthOfYear(); } return (days - 1); } 
-one
Nov 21 '11 at 17:52
source share



All Articles