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>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024