Java LocalDate Class | withDayOfMonth() method with Example

LocalDate Class withDayOfMonth() method: Here, we are going to learn about the withDayOfMonth() method of LocalDate Class with its syntax and example.
Submitted by Preeti Jain, on June 02, 2020

LocalDate Class withDayOfMonth() method

  • withDayOfMonth() method is available in java.time package.
  • withDayOfMonth() method is used to update this object with the given day-of-month (dd_of_mm) in this LocalDate.
  • withDayOfMonth() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • withDayOfMonth() method may throw an exception at the time of updating this object with the given day.
    DateTimeException: This exception may throw when the given parameter holds invalid value.

Syntax:

    public LocalDate withDayOfMonth(int dd_of_mm);

Parameter(s):

  • int dd_of_mm – represents the day-of-month by which to update this object and the number of days in a month starts from 1 and ends at 31.

Return value:

The return type of this method is LocalDate, it returns the LocalDate that holds the value to update the day-of-month of this object with the given day-of-month.

Example:

// Java program to demonstrate the example 
// of withDayOfMonth(int dd_of_mm) method of LocalDate

import java.time.*;

public class WithDayOfMonthOfLocalDate {
    public static void main(String args[]) {
        int day_of_month = 5;
        
        // Instantiates two LocalDate
        LocalDate l_da1 = LocalDate.parse("2007-04-04");
        LocalDate l_da2 = LocalDate.of(2008, Month.FEBRUARY, 06);

        // Display l_da1,l_da2 
        System.out.println("LocalDate l_da1,l_da2 : ");
        System.out.println("l_da1: " + l_da1);
        System.out.println("l_da2: " + l_da2);
        System.out.println("day_of_month to update: " + day_of_month);

        System.out.println();

        // Here, this method updates day-of-month 
        // with the given value in this LocalDate
        // l_da1
        LocalDate l_date = l_da1.withDayOfMonth(day_of_month);

        // Display l_date
        System.out.println("l_da1.withDayOfMonth(day_of_month): " + l_date);

        // Here, this method updates day-of-month
        // with the given day-of-month in this 
        // LocalDate l_da2
        l_date = l_da2.withDayOfMonth(day_of_month);

        // Display l_date
        System.out.println("l_da2.withDayOfMonth(day_of_month): " + l_date);
    }
}

Output

LocalDate l_da1,l_da2 : 
l_da1: 2007-04-04
l_da2: 2008-02-06
day_of_month to update: 5

l_da1.withDayOfMonth(day_of_month): 2007-04-05
l_da2.withDayOfMonth(day_of_month): 2008-02-05


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.