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.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            = 2021-10-29T06:40:17.373+08:00
First day of next month = 2021-11-01T00:00:00.000+08:00

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.