java offsetdatetime_Java OffsetDateTime with()用法及代码示例

在OffsetDateTime类中,根据传递给它的参数,有两种类型的with()方法。

with(TemporalAdjuster adjuster)

OffsetDateTime类的with(TemporalAdjuster Adjuster)方法,该方法用于使用TemporalAdjuster调整此OffsetDateTime,并在调整后返回调整后的OffsetDateTime的副本。使用指定的调整器策略对象进行调整。此OffsetDateTime实例是不可变的,不受此方法调用的影响。

用法:

public OffsetDateTime with(TemporalAdjuster adjuster)

参数:该方法接受调节器作为要使用的调节器的参数。

返回值:此方法基于此返回的OffsetDateTime进行调整。

异常:此方法引发以下异常:

DateTimeException–如果无法进行调整。

ArithmeticException–如果发生数字溢出。

以下示例程序旨在说明with()方法:

示例1:

// Java program to demonstrate

// OffsetDateTime.with() method

import java.time.*;

import java.time.temporal.*;

public class GFG {

public static void main(String[] args)

{

// create a OffsetDateTime object

OffsetDateTime off

= OffsetDateTime.parse("2018-12-12T13:30:30+05:00");

// print instance

System.out.println("OffsetDateTime before"

+ " adjustment: "

+ off);

// apply with method of OffsetDateTime class

OffsetDateTime updatedlocal

= off.with(Month.JUNE)

.with(TemporalAdjusters

.firstDayOfMonth());

// print instance

System.out.println("OffsetDateTime after"

+ " adjustment: "

+ updatedlocal);

}

}

输出:

OffsetDateTime before adjustment: 2018-12-12T13:30:30+05:00

OffsetDateTime after adjustment: 2018-06-01T13:30:30+05:00

with(TemporalField field, long newValue)

OffsetDateTime类的with(TemporalField field,long newValue)方法用于将OffsetDateTime的指定字段设置为新值并返回新时间的副本。此方法可用于更改任何受支持的字段,例如年份,月份或day-of-month。如果由于不支持该字段或其他原因而无法设置新值,则会引发异常。此OffsetDateTime实例是不可变的,不受此方法调用的影响。

用法:

public OffsetDateTime with(TemporalField field, long newValue)

参数:此方法接受作为结果中要设置的字段的field和作为结果中该字段的新值的newValue。

返回值:此方法基于此返回OffsetDateTime并带有指定的字段集。

异常:此方法引发以下异常:

DateTimeException–如果无法进行调整。

UnsupportedTemporalTypeException–如果不支持该字段。

ArithmeticException–如果发生数字溢出。

以下示例程序旨在说明with()方法:

示例1:

// Java program to demonstrate

// OffsetDateTime.with() method

import java.time.*;

import java.time.temporal.*;

public class GFG {

public static void main(String[] args)

{

// create a OffsetDateTime object

OffsetDateTime off

= OffsetDateTime.parse("2018-12-12T13:30:30+05:00");

// print instance

System.out.println("OffsetDateTime before"

+ " adjustment: "

+ off);

// apply with method of OffsetDateTime class

OffsetDateTime updatedlocal

= off.with(ChronoField.DAY_OF_MONTH, 31);

// print instance

System.out.println("OffsetDateTime after"

+ " applying method: "

+ updatedlocal);

}

}

输出:

OffsetDateTime before adjustment: 2018-12-12T13:30:30+05:00

OffsetDateTime after applying method: 2018-12-31T13:30:30+05:00

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值