我需要一年中的天数,并且我想使用Java8的新time api。
然而,我不能做Duration.ofDays(365)
,因为它没有考虑到闰年。因为java.time.temporal.UnsupportedTemporalTypeException: Unit must not have an estimated duration
,Duration.of(1, ChronoUnit.YEARS)
不能飞行
我查看了Period,但它对于从几年到几天似乎没有什么用处。
我觉得我错过了什么?如果一年是闰年,我可以写一些东西来添加一天,但似乎我应该能够开箱即用。
发布于 2015-04-27 15:13:45
根据Getting Duration using the new dateTime API中的响应,您应该使用
Period p = Period.ofYears(1);
理解Duration
(纳秒数<1天)和Period
(变量>1天)之间的区别是很重要的。
例如,Duration
不会考虑闰日、夏令时或闰秒,它的持续时间不到一天,最多只有几天。因此,如果您能够使用Period
来代替它,这将会更好。
因为不同的年份有不同的天数,所以如果您想要计算一年中的天数,您需要指定您正在讨论的年份。
如果您想要特定年份的天数,可以使用
Year.of(year).length()
如果您想要一年后的日期,您可以使用
LocalDate.now().plusYears(1)
或
LocalDate.now().plus(Period.ofYears(1))
如果需要两个日期之间的天数,可以使用
ChronoUnit.DAYS.between(start, end)
因此,要计算到一年后的天数,您可以使用
LocalDate today = LocalDate.now();
long days = ChronoUnit.DAYS.between(today, today.plusYears(1));
如果您想查看一年的会员资格是否仍然有效,您可以使用
Period membershipLength = Period.ofYears(1);
LocalDate membershipStart = ...;
LocalDate membershipEnd = membershipStart.plus(membershipLength);
LocalDate today = LocalDate.now();
boolean memberShipEnded = today.isAfter(membershipEnd);
boolean membershipValid = !membershipEnded;
发布于 2015-04-27 15:14:28
很明显,您不需要持续时间(=介于两个日期之间),而需要特定日期的年份长度。
LocalDate dateLeap = LocalDate.of(2004, Month.MARCH, 1);
System.out.println("leap year of " + dateLeap
+ " has days: " + dateLeap.lengthOfYear());
闰年2004-03-01有天: 366
Java 8的日期和时间是惊人的完整。
如果您的意思是,在2004年1月5日到2005年1月5日= 366和2004年3月2日到2005年3月2日= 365
int lengthOfYear(LocalDate date) {
return date.getMonthValue() <= 2
? date.lengthOfYear() // Count Feb in this year
: date.plusYears(1).lengthOfYear(); // Count Feb in next year
}
说明:基本上长度是365。但如果日期是>= 3月,则计算下一年的2月,否则计算今年的2月。
请注意,plusYears(1)
不会在一天或一个月内更改。
此外,也不考虑2月29日的闰秒和小时/分钟。
https://stackoverflow.com/questions/29899299
复制