Java中的 ZonedDateTime minusMonths() 方法及示例
ZonedDateTime类的minusMonths()方法,用于减去此 ZonedDateTime 中的月数,并在减去后返回 ZonedDateTime 的副本。此实例是不可变的,不受此方法调用的影响。
句法:
public ZonedDateTime minusMonths(long months)
参数:此方法接受单个参数months ,表示要减去的月份,可以为负数。
返回值:此方法返回基于此日期时间减去月份的ZonedDateTime ,而不是 null。
异常:如果结果超出支持的日期范围,此方法将引发DateTimeException 。
下面的程序说明了 minusMonths() 方法:
方案一:
// Java program to demonstrate
// ZonedDateTime.minusMonths() method
import java.time.*;
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"
+ " subtracting months: "
+ zoneddatetime);
// subtract 10 months
ZonedDateTime returnvalue
= zoneddatetime.minusMonths(10);
// print result
System.out.println("ZonedDateTime after "
+ " subtracting 10 months: "
+ returnvalue);
}
}
ZonedDateTime before subtracting months: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ZonedDateTime after subtracting 10 months: 2018-02-06T19:21:12.123+05:30[Asia/Calcutta]
方案二:
// Java program to demonstrate
// ZonedDateTime.minusMonths() method
import java.time.*;
public class GFG {
public static void main(String[] args)
{
// create a ZonedDateTime object
ZonedDateTime zoneddatetime
= ZonedDateTime.parse(
"2018-10-25T23:12:31.123+02:00[Europe/Paris]");
// print instance
System.out.println("ZonedDateTime before"
+ " subtracting months: "
+ zoneddatetime);
// subtract 2 months
ZonedDateTime returnvalue
= zoneddatetime.minusMonths(2);
// print result
System.out.println("ZonedDateTime after "
+ " subtracting 2 months: "
+ returnvalue);
}
}
ZonedDateTime before subtracting months: 2018-10-25T23:12:31.123+02:00[Europe/Paris]
ZonedDateTime after subtracting 2 months: 2018-08-25T23:12:31.123+02:00[Europe/Paris]
参考: https: Java/time/ZonedDateTime.html#minusMonths(long)