Android中季度日期范围判断及统计代码错误排查求助
问题分析与修复方案
我帮你找出了代码里的几个关键问题,咱们一个个拆解来看:
1. 日期解析格式不匹配
你的modifiedtime格式是dd-MM-yyyy(比如29-05-2020),但LocalDate.parse()默认使用ISO标准格式yyyy-MM-dd,直接解析会抛出DateTimeParseException,导致后续逻辑完全失效。
修复方法:指定对应格式的日期格式化器来解析:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); localModifiedDate = LocalDate.parse(opportunityModel.getModifiedtime(), formatter);
2. 日期范围判断逻辑完全颠倒
你写的条件:
if (firstDayOfQuarter.isAfter(localModifiedDate) && lastDayOfQuarter.isBefore(localModifiedDate))
这个逻辑的意思是“季度首日晚于修改日期 并且 季度末日早于修改日期”——这根本不可能同时成立,除非修改日期既在季度之前又在季度之后,所以这个条件永远不会触发!
正确的逻辑应该是判断修改日期大于等于季度首日,并且小于等于季度末日,可以这样写:
// Java 8+ 兼容写法 if (!firstDayOfQuarter.isAfter(localModifiedDate) && !lastDayOfQuarter.isBefore(localModifiedDate))
或者用Java 11+更直观的API:
if (localModifiedDate.isEqualOrAfter(firstDayOfQuarter) && localModifiedDate.isEqualOrBefore(lastDayOfQuarter))
3. 统计逻辑不符合需求
你用Collections.frequency(salesstage_list, "Opportunity")会直接统计整个列表中“Opportunity”的总次数,而不是仅统计日期符合条件的那些。根据你的需求,应该在遍历每个opportunity时,当日期符合条件才累加计数,而不是直接取整个列表的频率。
修复示例(假设你在遍历opportunity列表的循环中):
int countOpportunity = 0; // 遍历每个机会模型 for (OpportunityModel opportunityModel : opportunityList) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate localModifiedDate = LocalDate.parse(opportunityModel.getModifiedtime(), formatter); LocalDate localDate = LocalDate.now(); LocalDate firstDayOfQuarter = localDate.with(localDate.getMonth().firstMonthOfQuarter()) .with(TemporalAdjusters.firstDayOfMonth()); LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2) .with(TemporalAdjusters.lastDayOfMonth()); // 判断日期是否在季度范围内 if (localModifiedDate.isEqualOrAfter(firstDayOfQuarter) && localModifiedDate.isEqualOrBefore(lastDayOfQuarter)) { // 仅当该机会的状态是Opportunity时计数 if ("Opportunity".equals(opportunityModel.getSalesstage())) { countOpportunity++; } } } catch (DateTimeParseException e) { // 处理格式错误的日期,避免崩溃 Log.e("DateParseError", "Invalid date format: " + opportunityModel.getModifiedtime(), e); } } } System.out.println("Count_opportunity is: " + countOpportunity);
额外提醒
- 记得添加日期解析的异常处理,避免因非法日期字符串导致应用崩溃。
- 如果你的需求是判断修改日期所在季度而非当前日期的季度,那还需要调整季度的计算逻辑(基于修改日期来获取对应的季度首尾日)。
内容的提问来源于stack exchange,提问作者user13657604
相关产品推荐
相关产品推荐

