How do I get the first day of the next month in Joda-Time?

This example will give you the first day of the next month from the current system date. In the example we use the MutableDateTime class. MutableDateTime is a datetime class whose value can be modified.

In the code snippet we start by creating an instance of MutableDateTime class. We add 1 month from the current date using the addMonths() method. We set the day of the month to the first day using the setDayOfMonth() method. To make sure it is the first day we set the time to midnight by calling the setMillisOfDay() method.

package org.kodejava.example.joda;

import org.joda.time.MutableDateTime;

public class FirstDayOfNextMonth {
    public static void main(String[] args) {
        // Creates an instance of MutableDateTime for the current
        // system date time.
        MutableDateTime dateTime = new MutableDateTime();
        System.out.println("Current date            = " + dateTime);

        // Find the first day of the next month can be done by:
        // 1. Add 1 month to the date
        // 2. Set the day of the month to 1
        // 3. Set the millis of day to 0.
        dateTime.addMonths(1);
        dateTime.setDayOfMonth(1);
        dateTime.setMillisOfDay(0);
        System.out.println("First day of next month = " + dateTime);
    }
}

Here is an example result of the program:

Current date            = 2017-01-15T20:03:17.334+08:00
First day of next month = 2017-02-01T00:00:00.000+08:00

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, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply