Close

Java Date Time - OffsetDateTime.withMonth() Examples

Java Date Time Java Java API 


Class:

java.time.OffsetDateTime

java.lang.Objectjava.lang.Objectjava.time.OffsetDateTimejava.time.OffsetDateTimejava.time.temporal.TemporalTemporaljava.time.temporal.TemporalAdjusterTemporalAdjusterjava.lang.ComparableComparablejava.io.SerializableSerializableLogicBig

Method:

public OffsetDateTime withMonth(int month)

Returns a copy of this OffsetDateTime with month-of-year replaced with the provided 'month'



Examples


package com.logicbig.example.offsetdatetime;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class WithMonthExample {

public static void main(String... args) {
OffsetDateTime d = OffsetDateTime.of(2015, 10, 5, 15,
30, 10, 1000000, ZoneOffset.ofHours(-5));
System.out.println(d);

OffsetDateTime d2 = d.withMonth(5);
System.out.println(d2);
}
}

Output

2015-10-05T15:30:10.001-05:00
2015-05-05T15:30:10.001-05:00




If the provided month is invalid.

package com.logicbig.example.offsetdatetime;

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class WithMonthExample2 {

public static void main(String... args) {
OffsetDateTime d = OffsetDateTime.of(2015, 10, 5, 15,
30, 10, 1000000, ZoneOffset.ofHours(-5));
System.out.println(d);

OffsetDateTime d2 = d.withMonth(15);
System.out.println(d2);
}
}

Output

Caused by: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 15
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 java.time.LocalDateTime.withMonth(LocalDateTime.java:1006)
at java.time.OffsetDateTime.withMonth(OffsetDateTime.java:1011)
at com.logicbig.example.offsetdatetime.WithMonthExample2.main(WithMonthExample2.java:19)
... 6 more




See Also