Close

Java Date Time - Year.with() Examples

Java Date Time Java Java API 


Class:

java.time.Year

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

Methods:

public Year with(TemporalAdjuster adjuster)

Returns an adjusted copy of this year for the specified temporal adjuster.



public Year with(TemporalField field,
                 long newValue)

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


Examples


package com.logicbig.example.year;

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

public class WithExample {

public static void main(String... args) {
Year y = Year.of(1999);
System.out.println(y);

Year with = y.with(firstYearOfDecadeAdjuster);
System.out.println(with);

}

private static final TemporalAdjuster firstYearOfDecadeAdjuster = new TemporalAdjuster() {
@Override
public Temporal adjustInto(Temporal temporal) {
if (temporal.isSupported(ChronoField.YEAR)) {
int i = temporal.get(ChronoField.YEAR);
return Year.of((i / 10) * 10);
}
return null;
}
};
}

Output

1999
1990




package com.logicbig.example.year;

import java.time.Year;
import java.time.temporal.ChronoField;

public class WithExample2 {

public static void main(String... args) {
Year y = Year.of(2011);
System.out.println(y);

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

Output

2011
YEAR_OF_ERA => 1
YEAR => 1
ERA => 2011




See Also