Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I obtain the number of days within a given month using Joda-Time?

People also ask

What is Joda-time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.

Is Joda-time deprecated?

So the short answer to your question is: YES (deprecated).

What is Joda LocalDate?

LocalDate is an immutable datetime class representing a date without a time zone. LocalDate implements the ReadablePartial interface. To do this, the interface methods focus on the key fields - Year, MonthOfYear and DayOfMonth. However, all date fields may in fact be queried.

Does Joda DateTime have timezone?

Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone). Use proper time zone names.


If you have a DateTime object which represents a value in the month, then it's pretty straightforward. You get the dayOfMonth property from that DateTime object and get the maximum value of the property. Here is a sample function:

public static int daysOfMonth(int year, int month) {
  DateTime dateTime = new DateTime(year, month, 14, 12, 0, 0, 000);
  return dateTime.dayOfMonth().getMaximumValue();
}

Yes, although it's not as pretty as it might 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));
        }
    }
}

Note that I've hard-coded the assumption that there are 12 months, and that we're interested in 2010. I've explicitly selected the Gregorian chronology though - in other chronologies you'd get different answers, of course. (And the "12 month" loop wouldn't be a valid assumption either...)

I've gone for a LocalDate rather than a DateTime in order to fetch the value, to emphasize (however faintly :) that the value doesn't depend on the time zone.

This is still not as simple as it looks, mind you. I don't know off-hand what happens if use one chronology to construct the LocalDate, but ask for the maximum value of a field in a different chronology. I have some ideas about what might happen, knowing a certain amount about Joda Time, but it's probably not a good idea :)