Month adjustInto() method in Java
Last Updated :
22 Mar, 2019
The adjustInto() method of java.time.Month ENUM is an in-built function in Java which takes a Temporal object specifying a date and returns a new Temporal object of the same observable type as the input with the month replaced with this month-of-year.
Method Declaration:
public Temporal adjustInto(Temporal temporal)
Syntax:
Temporal newLocalDate = Month.ANYMONTH.adjustInto(Temporal temporal)
Parameters: This method takes temporal as parameter where:
- temporal – is the specified date to be adjusted.
- ANYMONTH – is the specified month to which the date is to be adjusted, e.g., JANUARY, FEBRUARY, etc.
- newLocalDate – is the modified date.
Return Value: The function returns an adjusted Temporal object which is the date adjusted according to specified Month.
Exceptions:
- DateTimeException: This method throws this exception if it is not possible to make the adjustment.
- ArithmeticException: This exception is thrown if numeric overflow occurs.
Below programs illustrate the above method:
Program 1:
import java.time.*;
import java.time.Month;
import java.time.temporal.Temporal;
class DayOfWeekExample {
public static void main(String[] args)
{
LocalDate localDate1
= LocalDate.of( 1947 , Month.AUGUST, 15 );
Month monthOfYear1
= Month.from(localDate1);
System.out.println(localDate1
+ " which is "
+ monthOfYear1.name());
Temporal localDate2
= Month.JANUARY
.adjustInto(localDate1);
Month monthOfYear2
= Month.from(localDate2);
System.out.println(localDate2
+ " which is "
+ monthOfYear2.name());
}
}
|
Output:
1947-08-15 which is AUGUST
1947-01-15 which is JANUARY
Program 2:
import java.time.*;
import java.time.Month;
import java.time.temporal.Temporal;
class DayOfWeekExample {
public static void main(String[] args)
{
LocalDate localDate1
= LocalDate.of( 2019 , Month.MARCH, 18 );
Month monthOfYear1
= Month.from(localDate1);
System.out.println(localDate1
+ " which is "
+ monthOfYear1.name());
Temporal localDate2
= Month.DECEMBER
.adjustInto(localDate1);
Month monthOfYear2
= Month.from(localDate2);
System.out.println(localDate2
+ " which is "
+ monthOfYear2.name());
}
}
|
Output:
2019-03-18 which is MARCH
2019-12-18 which is DECEMBER
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#adjustInto-java.time.temporal.Temporal-
Share your thoughts in the comments
Please Login to comment...