Java Period from()方法及示例
Java中Period类的from()方法用于从给定的时间量中获得一个Period的实例。
这个函数根据参数中给定的数量获得一个周期。TemporalAmount代表一个时间量,它可以是基于日期的,也可以是基于时间的。
语法
public static Period from(TemporalAmount amount)
参数: 该方法接受一个单一参数 amount 。这个金额是我们需要转换为周期的金额。
返回值: 该函数返回相当于给定金额的周期。
异常情况
DateTimeException – 如果不能转换为周期,它会抛出DateTimeException。ArithmeticException – 如果年、月、日的数量超过了一个int,它将抛出ArithmeticException。下面的程序说明了上述方法。
// Java code to show the function from()// which represents the period of given amountimport java.time.Period; public class PeriodClassGfG { // Function to convert given amount to period static void convertToPeriod(int year, int months, int days) { Period period = Period.from(Period.of(year, months, days)); System.out.println(period); } // Driver code public static void main(String[] args) { int year = 20, months = 13, days = 17; Period period = Period.from(Period.of(year, months, days)); convertToPeriod(year, months, days); }}
输出:
P20Y13M17D
参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#from-java.time.temporal.TemporalAmount-
