在LocalDate类中,根据传递给它的参数,有两种类型的with()方法。
with(TemporalAdjuster adjuster)
LocalDate类的with(TemporalAdjuster Adjuster)方法用于使用传递的TemporalAdjuster作为参数来调整此日期时间,并在调整后返回调整后的日期时间的副本。使用指定的调整器策略对象进行调整。该LocalDate实例是不可变的,不受此方法调用的影响。
用法:
public LocalDate with(TemporalAdjuster adjuster)
参数:该方法接受调节器作为要使用的调节器的参数。
返回值:该方法将基于此方法返回LocalDate并进行调整。
异常:此方法引发以下异常:
DateTimeException–如果无法进行调整。
ArithmeticException–如果发生数字溢出。
以下示例程序旨在说明with()方法:
示例1:
// Java program to demonstrate
// LocalDate.with() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a LocalDate object
LocalDate local
= LocalDate.parse(
"2018-12-06");
// print instance
System.out.println("LocalDate before"
+ " adjustment: "
+ local);
// apply with method of LocalDate class
LocalDate updatedlocal
= local.with(Month.MARCH)
.with(TemporalAdjusters
.lastDayOfMonth());
// print instance
System.out.println("LocalDate after"
+ " adjustment: "
+ updatedlocal);
}
}
输出:
LocalDate before adjustment: 2018-12-06
LocalDate after adjustment: 2018-03-31
with(TemporalField field, long newValue)
with(TemporalField字段,长newValue)LocalDate类的方法,用于将LocalDate的指定字段设置为新值并返回新的日期时间的副本。此方法可用于更改任何受支持的字段,例如年,月或day-of-month。如果由于不支持该字段或其他原因而无法设置新值,则会引发异常。
在某些情况下,更改指定的字段可能会导致结果日期时间变为无效,例如将月份从1月31日更改为2月将使day-of-month无效。在这种情况下,该字段负责解决日期。通常,它将选择上一个有效日期,在此示例中,该日期将是2月的最后一个有效日期。该LocalDate实例是不可变的,不受此方法调用的影响。
用法:
public LocalDate with(TemporalField field, long newValue)
参数:此方法接受作为结果中要设置的字段的field和作为结果中该字段的新值的newValue。
返回值:该方法基于此方法并使用指定的字段集返回LocalDate。
异常:此方法引发以下异常:
DateTimeException–如果无法进行调整。
UnsupportedTemporalTypeException–如果不支持该字段。
ArithmeticException–如果发生数字溢出。
以下示例程序旨在说明with()方法:
示例1:
// Java program to demonstrate
// LocalDate.with() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a LocalDate object
LocalDate local
= LocalDate.parse(
"2018-12-06");
// print instance
System.out.println("LocalDate before"
+ " applying method: "
+ local);
// apply with method of LocalDate class
LocalDate updatedlocal
= local.with(
ChronoField.DAY_OF_MONTH, 30);
// print instance
System.out.println("LocalDate after"
+ " applying method: "
+ updatedlocal);
}
}
输出:
LocalDate before applying method: 2018-12-06
LocalDate after applying method: 2018-12-30