How do I get the last day of a month in Joda-Time?

This example show us how to use Joda-Time’s DateTime class to get the last day of the month. To get the last day of the month we first need to find out the last date of the month. To do this, create a new instance of a DateTime. From the DateTime object get the day-of-the-month property by calling the dayOfMonth() method. Then call the withMaximumValue() method which will give us the last date of a month.

To get the day name, we call the DateTime‘s dayOfWeek() method followed by a call to the getAsText() method to get the name of the day. Let’s see the code snippet below:

package org.kodejava.joda;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

public class LastDayOfTheMonth {
    public static void main(String[] args) {
        // Creates an instance of DateTime.
        DateTime dateTime = DateTime.now();

        // Get the last date of the month using the dayOfMonth property
        // and get the maximum value from it.
        DateTime lastDate = dateTime.dayOfMonth().withMaximumValue();

        // Print the date and day name.
        System.out.println("Last date of the month = " + lastDate);
        System.out.println("Last day of the month  = " +
                lastDate.dayOfWeek().getAsText());

        // If you know the last date of the month you can simply parse the
        // date string and get the name of the last day of the month.
        String day = LocalDate.parse("2021-10-31").dayOfWeek().getAsText();
        System.out.println("Day  = " + day);
    }
}

If you know the last date of the month you can simply parse the date string to create a DateTime object or a LocalDate object and call the dayOfWeek() method and get the name of the day using getAsText() method.

The example output is:

Last date of the month = 2021-10-31T06:37:18.069+08:00
Last day of the month  = Sunday
Day  = Sunday

Maven Dependencies

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.12.5</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.