gpt4 book ai didi

java - 收集一段时间内每个月的天数

转载 作者:行者123 更新时间:2023-12-01 09:47:09 24 4
gpt4 key购买 nike

我被困在这个问题上好几天了,我搜索了很多,我在 java swing 程序中使用 jodatime 库所以这就是我需要的从 2013-04-17 到 2013-05-21我需要输出这样的结果:

  • 2013 年 4 月(天数 = 14)
  • 2013 年 5 月(天数 = 21)

我尝试了很多但没有解决方案,很生气:(删除所有代码并来这里寻求帮助任何帮助,将不胜感激。提前致谢

最佳答案

java.time

Joda-Time团队建议我们迁移到 java.time Java 8 及更高版本中内置的框架。 java.time 框架的大部分内容已 back-ported to Java 6 & 7以及进一步adapted to Android .

LocalDate类表示仅日期值,没有时间和时区。

LocalDate start = LocalDate.parse ( "2013-04-17" );
LocalDate stop = LocalDate.parse ( "2013-05-21" );
if ( stop.isBefore ( start ) ) {
System.out.println ( "ERROR - stop before start" );
// FIXME: Handle error.
}

YearMonth类代表一年和一个月的总和。非常适合跟踪您想要的结果。使用此类可以使您的代码类型安全并保证有效值,而不是仅使用字符串或数字。

YearMonth startYm = YearMonth.from ( start );
YearMonth stopYm = YearMonth.from ( stop );

我们创建一个SortedMap其中 YearMonth 键映射到 Integer 值(天数)来收集我们的结果。 TreeMap是我们选择的实现。

SortedMap<YearMonth , Integer> map = new TreeMap<> ();

示例代码并不假设我们只过渡几个月。如果中间有多个月份,我们会询问 YearMonth 该月的天数。我们通过 YearMonth 循环 YearMonth,每次获取天数。

我们对五种可能情况中的每一种进行 if-else 测试:

  • 单月
    • 开始和结束都在一个月内。
  • 多个月
    • 第一个月
    • 任何中间月份
    • 上个月
  • 不可能否则
    • 除非我们在逻辑或编码中犯了错误,否则应该无法到达。

在每种情况下,我们都会捕获该 YearMonth 的收集天数。

当调用 Between 方法时,我们必须调整它使用Half-Open方法来处理时间跨度。在这种方法中,开始是包含,而结尾是排除。一般来说,这是最好的路线。但问题中的逻辑是相反的,所以我们进行调整。我强烈建议撤消这些调整并调整您的输入。一致使用 Half-Open 将使日期时间处理变得更加容易。

YearMonth yearMonth = startYm;
do {
int days = 0;
if ( startYm.equals ( stopYm ) ) { // If within the same (single) month.
days = ( int ) ChronoUnit.DAYS.between ( start , stop );
} else if ( yearMonth.equals ( startYm ) ) { // If on the first month of multiple months, count days.
days = ( int ) ChronoUnit.DAYS.between ( start , startYm.plusMonths ( 1 ).atDay ( 1 ) ); // Get first of next month, to accommodate the `between` method’s use of Half-Open logic.
} else if ( yearMonth.isAfter ( startYm ) && yearMonth.isBefore ( stopYm ) ) { // If on the in-between months, ask for the days of that month.
days = yearMonth.lengthOfMonth ();
} else if ( yearMonth.equals ( stopYm ) ) { // If on the last of multiple months.
days = ( int ) ChronoUnit.DAYS.between ( stopYm.atDay ( 1 ).minusDays ( 1 ) , stop ); // Get last day of previous month, to accommodate the `between` method’s use of Half-Open logic.
} else {
System.out.println ( "ERROR - Reached impossible point." );
// FIXME: Handle error condition.
}
map.put ( yearMonth , days ); // Cast long to int, auto-boxed to Integer.
// Prep for next loop.
yearMonth = yearMonth.plusMonths ( 1 );
} while ( ! yearMonth.isAfter ( stopYm ) );

转储到控制台。

System.out.println ( "start: " + start + " | stop: " + stop + " | map: " + map );

start: 2013-04-17 | stop: 2013-05-21 | map: {2013-04=14, 2013-05=21}

关于java - 收集一段时间内每个月的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37896525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com