Write a Java program to get the months remaining in the year
This program demonstrates how to calculate the number of remaining months in the current year.
- The java.time package is used to work with date and time classes. In the first line, we import all the classes in the package.
- Next, we define the class Month_Remaining which contains the main method.
- In the main method, we create a LocalDate object t which represents the current date. We then use the TemporalAdjusters.lastDayOfYear() method to get the last day of the current year, which is assigned to the lastDayOfYear variable.
- We then create a Period object period which represents the time period between the current date t and the last day of the year lastDayOfYear. We calculate the number of remaining months in the current year using the getMonths() method of the Period class.
- Finally, we print the number of remaining months in the current year using the System.out.println() method.
Source Code
import java.time.*;
import java.time.temporal.TemporalAdjusters;
class Month_Remaining
{
public static void main(String[] args)
{
LocalDate t = LocalDate.now();
LocalDate lastDayOfYear = t.with(TemporalAdjusters.lastDayOfYear());
Period period = t.until(lastDayOfYear);
System.out.println("Months Remaining in the Year : "+period.getMonths());
}
}
Output
Months Remaining in the Year : 1