Java ZonedDateTime with()方法及示例
在ZonedDateTime类中,根据传递给它的参数,有两种类型的with()方法。
with(TemporalAdjuster adjuster)
ZonedDateTime 类的 with(TemporalAdjuster adjuster) 方法用于调整这个日期时间,调整后返回调整后的日期时间的副本。ZonedDateTime的这个实例是不可改变的,不受这个方法调用的影响。
语法
public ZonedDateTime with(TemporalAdjuster adjuster)
参数: 该方法接受 调整器 作为参数,它是要使用的调整器。
返回值: 该方法返回一个基于此的ZonedDateTime,并进行调整。
异常: 该方法会抛出以下异常。
- DateTimeException – 如果不能进行调整。
- ArithmeticException – 如果发生数字溢出。
下面的程序说明了with()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.with() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a ZonedDateTime object
ZonedDateTime zoneddatetime
= ZonedDateTime.parse(
"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
// print instance
System.out.println("ZonedDateTime before"
+ " adjustment: "
+ zoneddatetime);
// apply with method of ZonedDateTime class
ZonedDateTime zt
= zoneddatetime
.with(Month.SEPTEMBER)
.with(TemporalAdjusters.firstDayOfMonth());
// print instance
System.out.println("ZonedDateTime after"
+ " adjustment: "
+ zt);
}
}
输出。
ZonedDateTime before adjustment: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after adjustment: 2018-09-01T19:21:12.123+05:30[Asia/Calcutta]
with(TemporalField field, long newValue)
with(TemporalField field, long newValue) 方法是 ZonedDateTime 类的方法,用于将指定的字段设置为一个新的值,并返回新日期时间的副本。这个方法可以用来改变任何支持的字段,如年、月、日。
在某些情况下,改变指定的字段会导致生成的日期时间无效,例如将月份从1月31日改为2月会使月日无效。在这样的情况下,该字段负责解决日期问题。通常情况下,它会选择之前的有效日期,也就是本例中2月份的最后一个有效日期。ZonedDateTime的这个实例是不可改变的,不受这个方法调用的影响。
语法
public ZonedDateTime with(TemporalField field, long newValue)
参数: 该方法接受 field 和 newValue 作为参数,前者是要在结果中设置的字段,后者是结果中该字段的新值。
返回值: 该方法返回一个基于指定字段设置的ZonedDateTime。
异常: 该方法会抛出以下异常。
- DateTimeException – 如果不能进行调整。
- UnsupportedTemporalTypeException – 如果该字段不被支持。
- ArithmeticException – 如果发生数字溢出。
以下程序说明了with()方法:
程序1 :
// Java program to demonstrate
// ZonedDateTime.with() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// create a ZonedDateTime object
ZonedDateTime zoneddatetime
= ZonedDateTime.parse(
"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
// print instance
System.out.println("ZonedDateTime before"
+ " applying method: "
+ zoneddatetime);
// apply with method of ZonedDateTime class
ZonedDateTime zt
= zoneddatetime.with(
ChronoField.HOUR_OF_DAY, 13);
// print instance
System.out.println("ZonedDateTime after"
+ " applying method: "
+ zt);
}
}
输出。
ZonedDateTime before applying method: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after applying method: 2018-12-06T13:21:12.123+05:30[Asia/Calcutta]
参考文献:
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#with(java.time.temporal.TemporalField, long)
https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#with(java.time.temporal.TemporalAdjuster)