如何计算一个时期的天数? [英] How to calculate the number of days in a period?

查看:31
本文介绍了如何计算一个时期的天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下Period计算:

Period.between(LocalDate.of(2015, 8, 1), LocalDate.of(2015, 9, 2))

结果是:

P1M1D

这相当于 31 天 + 1 天 = 32 天.

对于这个Period:

Period.between(LocalDate.of(2015, 8, 1), LocalDate.of(2015, 10, 2))

结果是:

P2M1D

这相当于:31 天(八月)+ 30 天(九月)+ 1(十月)= 62 天

java.time 包中是否有一种方法可以给出Period 中的天数?我找不到一个.不确定我是否忽略了任何东西,或者它只是不存在.

解决方案

来自文档

一个>:

<块引用>

使用基于日期的值(年、月、天),使用 Period 类.Period 类提供了各种 get方法,例如 getMonthsgetDaysgetYears.表示在单个时间单位(例如天)中测量的时间量,您可以使用ChronoUnit.between 方法.

LocalDate today = LocalDate.now();LocalDate 生日 = LocalDate.of(1960, Month.JANUARY, 1);Period p = Period.between(生日,今天);long p2 = ChronoUnit.DAYS.between(生日,今天);System.out.println("你是 " + p.getYears() + " 年," + p.getMonths() +" 月和 " + p.getDays() +" 天数.(" + p2 + " 总天数)");

代码产生类似于以下的输出:

你今年 53 岁零 4 个月零 29 天.(共19508天)

For the following Period calculation:

Period.between(LocalDate.of(2015, 8, 1), LocalDate.of(2015, 9, 2))

the result is:

P1M1D

This is equivalent to 31 days + 1 day = 32 days.

For this Period:

Period.between(LocalDate.of(2015, 8, 1), LocalDate.of(2015, 10, 2))

the result is:

P2M1D

This is equivalent to: 31 days (in August) + 30 days (in September) + 1 (in October) = 62 days

Is there a method in the java.time package which will give the number of days in a Period? I can't find one. Not sure if I have overlooked anything or if it is just plain not there.

解决方案

From the documentation:

To define an amount of time with date-based values (years, months, days), use the Period class. The Period class provides various get methods, such as getMonths, getDays, and getYears.To present the amount >of time measured in a single unit of time, such as days, you can use the ChronoUnit.between method.

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);

Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
                   " months, and " + p.getDays() +
                   " days old. (" + p2 + " days total)");

The code produces output similar to the following:

You are 53 years, 4 months, and 29 days old. (19508 days total)

这篇关于如何计算一个时期的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆