给定持续时间时计算特定月份的天数 [英] Counting number of days of a particular month when given a duration
问题描述
给出了持续时间. 例如:1月15日至3月15日
A duration is given. Ex: Jan 15-March 15
在给定的持续时间内,我想计算每个月的天数. 在这个例子中 该持续时间中一月的天数; 15 该持续时间中2月的天数; 28岁 该持续时间中3月的天数; 15
I want to count the number of days which belongs to each month, in that given duration. In this example, number of days of January in that duration; 15 number of days of February in that duration; 28 number of days of March in that duration; 15
我正在寻找一种解决方案,它遍历持续时间的每个日期并检查是否Date.getMonth() = "Month I want to check against"
I'm looking for a solution other that traversing through each date of the duration and checking if Date.getMonth() = "Month I want to check against"
是否有使用Java Date或Java SQL Date中的方法或使用任何其他Date类型的简便方法?
Is there an easier way of doing this using methods in Java Date or Java SQL Date or using any other Date type?
推荐答案
Map < YearMonth , Long >
具有lambda语法
这是一个使用流和lambda的简短代码的解决方案.尽管此解决方案确实遍历了时间范围的每个日期,但是代码的简单性和清晰度可能会超过这种低效率.
Map < YearMonth , Long >
with lambda syntax
Here is a solution using a bit of terse code using streams and lambdas. While this solution does traverse each date of the time range, the simplicity and clarity of the code may outweigh that inefficiency.
使用 LocalDate
作为开始和结束日期.使用 YearMonth
进行每月跟踪.
Use LocalDate
for the starting and stopping date. Use YearMonth
to track each month.
LocalDate start = LocalDate.of( 2019 , 1 , 15 );
LocalDate stop = LocalDate.of( 2019 , 3 , 16 );
制作 Map
,每个月保留几天的时间.
Make a Map
to keep a number of days for each month.
Map < YearMonth, Long > map =
start
.datesUntil( stop )
.collect(
Collectors.groupingBy(
( LocalDate localDate ) -> YearMonth.from( localDate ) ,
TreeMap::new ,
Collectors.counting()
)
);
转储到控制台.
{2019-01 = 17,2019-02 = 28,2019-03 = 15}
{2019-01=17, 2019-02=28, 2019-03=15}
System.out.println( map );
-
给出开始日期, 然后只需将其分组为
TreeMap
)以按时间顺序排列月份,并按Then just do a grouping into a
SortedMap
(aTreeMap
) to keep months in chronological order, classified by theYearMonth
and counting the days for that month in the range.如果您希望一整天都可以做
If you want the total days you can just do
long totalDays = d.datesUntil(LocalDate.of(2019, 3, 16)).count();
这篇关于给定持续时间时计算特定月份的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!