Android:将数据库存储的年月转换为日期格式并匹配数组中的当前年月
解决Android中数据库年月转换日期并匹配的问题
你当前代码存在两个核心问题,导致无法正确解析日期并完成匹配:
- 拼接的年月字符串(比如
032024)和使用的SimpleDateFormat("yyyy-MM-dd")格式完全不匹配,解析必然失败; - 方法最终返回的是原始拼接的字符串列表,而非解析后的日期对象列表,无法直接进行日期维度的匹配。
步骤1:修正日期解析逻辑
首先要把数据库取出的月份和年份拼成可解析的格式,再用对应格式的解析器转换为日期对象。
兼容低版本的SimpleDateFormat实现
private ArrayList<Date> getGspApprovedMonthData() { ArrayList<Date> dates = new ArrayList<>(); SqlDataStore sd = new SqlDataStore(this); sd.open(); String gspQuery = " SELECT * FROM " + TABLE_GSP_APPROVED_DATA; Cursor gspCu = sd.getData(gspQuery); if (gspCu.moveToFirst()) { do { String gspMonth = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_MONTH)); String gspYr = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_YEAR)); // 拼接为yyyy-MM格式(如"2024-03") String dateStr = gspYr + "-" + gspMonth; // 使用对应格式的解析器 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM", Locale.getDefault()); try { Date date = sdf.parse(dateStr); dates.add(date); } catch (ParseException e) { e.printStackTrace(); } } while (gspCu.moveToNext()); } gspCu.close(); sd.close(); return dates; }
步骤2:实现与当前年月的匹配
获取当前系统的年月,遍历解析后的日期列表,对比每个日期的年月是否一致:
// 获取当前年月(Calendar月份从0开始,需+1转换为实际月份) Calendar currentCal = Calendar.getInstance(); int currentYear = currentCal.get(Calendar.YEAR); int currentMonth = currentCal.get(Calendar.MONTH) + 1; ArrayList<Date> approvedDates = getGspApprovedMonthData(); for (Date date : approvedDates) { Calendar dateCal = Calendar.getInstance(); dateCal.setTime(date); int year = dateCal.get(Calendar.YEAR); int month = dateCal.get(Calendar.MONTH) + 1; if (year == currentYear && month == currentMonth) { // 匹配成功,执行你的业务逻辑 Log.d("DateMatch", "找到匹配的年月:" + year + "-" + month); break; } }
推荐方案:使用Java 8+ DateTimeAPI(更安全可靠)
SimpleDateFormat是线程不安全的,Android API 26及以上可直接使用LocalDate,低版本可引入ThreeTenABP库兼容。
日期解析实现
private ArrayList<LocalDate> getGspApprovedMonthData() { ArrayList<LocalDate> dates = new ArrayList<>(); SqlDataStore sd = new SqlDataStore(this); sd.open(); String gspQuery = " SELECT * FROM " + TABLE_GSP_APPROVED_DATA; Cursor gspCu = sd.getData(gspQuery); if (gspCu.moveToFirst()) { do { String gspMonth = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_MONTH)); String gspYr = gspCu.getString(gspCu.getColumnIndex(Queryclass.GSP_APPROVED_YEAR)); // 直接转换为LocalDate,默认取当月第一天 LocalDate date = LocalDate.of(Integer.parseInt(gspYr), Integer.parseInt(gspMonth), 1); dates.add(date); } while (gspCu.moveToNext()); } gspCu.close(); sd.close(); return dates; }
匹配当前年月
// 获取当前年月 LocalDate currentDate = LocalDate.now(); int currentYear = currentDate.getYear(); int currentMonth = currentDate.getMonthValue(); ArrayList<LocalDate> approvedDates = getGspApprovedMonthData(); for (LocalDate date : approvedDates) { if (date.getYear() == currentYear && date.getMonthValue() == currentMonth) { // 匹配成功,执行你的业务逻辑 Log.d("DateMatch", "找到匹配的年月:" + currentYear + "-" + currentMonth); break; } }
内容的提问来源于stack exchange,提问作者Abm
相关产品推荐
相关产品推荐

