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.example.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("Date = " + lastDate.toString());
        System.out.println("Day  = " + 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("2017-01-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:

Date = 2017-01-31T15:00:24.838+08:00
Day  = Tuesday
Day  = Tuesday

Maven Dependencies

<!-- http://repo1.maven.org/maven2/joda-time/joda-time/2.9.7/joda-time-2.9.7.jar -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.7</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply