Open In App

MonthDay with() Method in Java with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

with(Month month) method of the MonthDay class used to alter the month-of-year of MonthDay object using month passed as a parameter and after that method returns the copy of altered MonthDay.If the day-of-month value is invalid for the specified month after altering operation, the day will be adjusted to the last valid day-of-month.

Syntax:

public MonthDay with(Month month)

Parameters: This method accepts month as parameter which is the month-of-year to set in the returned month-day.

Return value: This method returns a MonthDay based on this month-day with the requested month

Below programs illustrate the with() method:
Program 1:




// Java program to demonstrate
// MonthDay.with() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a MonthDay object
        MonthDay monthday
            = MonthDay.of(8, 28);
  
        // print instance
        System.out.println("MonthDay before"
                           + " applying method: "
                           + monthday);
  
        // apply with method of MonthDay class
        MonthDay updatedlocal
            = monthday.with(Month.OCTOBER);
  
        // print instance
        System.out.println("MonthDay after"
                           + " applying method: "
                           + updatedlocal);
    }
}


Output:

MonthDay before applying method: --08-28
MonthDay after applying method: --10-28

Program 2:




// Java program to demonstrate
// MonthDay.with() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a MonthDay object
        MonthDay monthday
            = MonthDay.of(10, 31);
  
        // print instance
        System.out.println("MonthDay before"
                           + " applying method: "
                           + monthday);
  
        // apply with method of MonthDay class
        MonthDay updatedlocal
            = monthday.with(Month.FEBRUARY);
  
        // print instance
        System.out.println("MonthDay after"
                           + " applying method: "
                           + updatedlocal);
    }
}


Output:

MonthDay before applying method: --10-31
MonthDay after applying method: --02-29

References: https://docs.oracle.com/javase/10/docs/api/java/time/MonthDay.html#with(java.time.Month)



Last Updated : 15 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads