The following example show you how to get the length of a month represented by a java.time.LocalDate
and a java.time.YearMonth
objects. Both of these classes have a method called lengthOfMonth()
that returns the length of month in days represented by those date objects.
package org.kodejava.datetime;
import java.time.LocalDate;
import java.time.Month;
import java.time.YearMonth;
public class LengthOfMonth {
public static void main(String[] args) {
// Get the length of month of the current date.
LocalDate date = LocalDate.now();
System.out.printf("%s: %d%n%n", date, date.lengthOfMonth());
// Get the length of month of a year-month combination value
// represented by the YearMonth object.
YearMonth yearMonth = YearMonth.of(2020, Month.FEBRUARY);
System.out.printf("%s: %d%n%n", yearMonth, yearMonth.lengthOfMonth());
// Repeat a process the get the length of a month for one-year
// period.
for (int month = 1; month <= 12; month++) {
yearMonth = YearMonth.of(2021, Month.of(month));
System.out.printf("%s: %d%n", yearMonth, yearMonth.lengthOfMonth());
}
}
}
The main()
method above start by showing you how to get the month length of a LocalDate
object. First we create a LocalDate
object using the LocalDate.now()
static factory method which return today’s date. And then we print out the length of month of today’s date on the following line.
The next snippet use the YearMonth
class. We begin by creating a YearMonth
object that represent the month of February 2020. We created it using the YearMonth.of()
static factory method. We then print out the length of month for those year-month combination.
In the last lines of the example we create a for loop to get all month’s length for the year of 2021 from January to December.
And here are the result of our code snippet above:
2021-11-16: 30
2020-02: 29
2021-01: 31
2021-02: 28
2021-03: 31
2021-04: 30
2021-05: 31
2021-06: 30
2021-07: 31
2021-08: 31
2021-09: 30
2021-10: 31
2021-11: 30
2021-12: 31
- 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