【发布时间】:2019-12-23 11:16:18
【问题描述】:
我正在显示 ArrayList 中的某些日期,并使用格式化程序将日期缩短为“dd/MM”,但是当我比较日期时,它不适用于月份。例如17/08 IS 在 19/08 之前,21/08 IS 在 19/08 之后,但 17/09 IS 在 19/08 之前。我的程序实现的是显示未来 8 天内的任何日期。
我已尝试使用 .compareTo 来执行此操作,它在一个月内有效,但在几个月之间无效。我知道它在比较字符串,我认为这是问题所在,但我不知道如何解决它
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
Calendar cal = Calendar.getInstance();
Date comDate = new Date();
cal.add(Calendar.DATE, 8);
//this adds days to the calender
comDate = cal.getTime();
String strDate = formatter.format(comDate);
//this applies the edited calender to the date I'm comparing to
ArrayList<String> arDat = new ArrayList<String>();
arDat.add("15/08");
arDat.add("15/09");
arDat.add("30/08");
Date recDate = new Date();
for (int i=0; i < arDat.size(); i++){
recDate = formatter.parse(arDat(i));
String strRecDate = formatter.format(recDate);
if (strRecDate.compareTo(strDate) < 0 {
showToast(recDate);
}
}
我希望它只显示 15/08,但它显示 15/08 和 15/09
【问题讨论】:
-
你在 java 8 日期时间 API 中使用了新库
-
仅供参考,
java.util.Date、java.util.Calendar和java.text.SimpleDateFormat等麻烦的日期时间类现在已被 java.time 类所取代。大多数 java.time 功能在 ThreeTen-Backport 项目中被反向移植到 Java 6 和 Java 7。进一步适用于ThreeTenABP 中的早期 Android (How to use ThreeTenABP…。 -
我建议你不要使用
SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的MonthDay和DateTimeFormatter。
标签: java date simpledateformat date-formatting compareto