Close

Java Date Time - YearMonth.with() Examples

Java Date Time Java Java API 


Class:

java.time.YearMonth

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

Methods:

public YearMonth with(TemporalAdjuster adjuster)

Returns an copy of this year-month, adjusted by the specified adjuster.



public YearMonth with(TemporalField field,
                      long newValue)

Returns a copy of this year-month with the specified field set to the specified new value.


Examples


package com.logicbig.example.yearmonth;

import java.time.YearMonth;
import java.time.temporal.ChronoField;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;

public class WithExample {
public static void main(String... args) {
YearMonth y = YearMonth.of(1970, 4);
System.out.println(y);

YearMonth y2 = y.with(midYearAdjuster);
System.out.println(y2);

}

private static final TemporalAdjuster midYearAdjuster = new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal temporal) {
if (temporal.isSupported(ChronoField.YEAR) &&
temporal.isSupported(ChronoField.MONTH_OF_YEAR)) {
int year = temporal.get(ChronoField.YEAR);
return YearMonth.of(year, 6);
}
return null;
}
};
}

Output

1970-04
1970-06




package com.logicbig.example.yearmonth;

import java.time.YearMonth;
import java.time.temporal.ChronoField;

public class WithExample2 {

public static void main(String... args) {
YearMonth y = YearMonth.of(2025, 5);
System.out.println(y);

for (ChronoField chronoField : ChronoField.values()) {
if (y.isSupported(chronoField)) {
YearMonth y2 = y.with(chronoField, 1);
System.out.printf("%15s => %s%n", chronoField.name(), y2);
}
}
}
}

Output

2025-05
MONTH_OF_YEAR => 2025-01
PROLEPTIC_MONTH => 0000-02
YEAR_OF_ERA => 0001-05
YEAR => 0001-05
ERA => 2025-05




See Also