Close

Java Date Time - LocalDate.withMonth() Examples

Java Date Time Java Java API 


Class:

java.time.LocalDate

java.lang.Objectjava.lang.Objectjava.time.LocalDatejava.time.LocalDatejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.time.chrono.ChronoLocalDateChronoLocalDatejava.io.SerializableSerializableLogicBig

Method:

public LocalDate withMonth(int month)

This method returns a new copy of this local date, with 'month-of-year' field replaced with the provided 'month' value.

If the provided month is invalid, an exception is thrown.


Examples


package com.logicbig.example.localdate;

import java.time.LocalDate;

public class WithMonthExample {

public static void main (String... args) {
LocalDate d = LocalDate.of(2016, 5, 10);
LocalDate d1 = d.withMonth(12);
System.out.println(d1);
}
}

Output

2016-12-10




An invalid value of month will cause DateTimeException.

package com.logicbig.example.localdate;

import java.time.LocalDate;

public class WithMonthExample2 {

public static void main (String... args) {
LocalDate d = LocalDate.of(2016, 5, 10);
LocalDate d1 = d.withMonth(13);
System.out.println(d1);
}
}

Output

Caused by: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 13
at java.time.temporal.ValueRange.checkValidValue(ValueRange.java:311)
at java.time.temporal.ChronoField.checkValidValue(ChronoField.java:703)
at java.time.LocalDate.withMonth(LocalDate.java:1079)
at com.logicbig.example.localdate.WithMonthExample2.main(WithMonthExample2.java:15)
... 6 more




See Also