我的 java 应用程序中有一个表示日期的字符串列表。格式为 yyyy/MM/dd。我希望能够获取所有这些字符串并将它们转换为实际的日期对象,以便可以对它们执行算术运算。
基本上我想浏览列表并删除已经发生的日期。我附上了代码。
List<String> datesList = new ArrayList<String>();
datesList.add("2011-11-01");
datesList.add("2015-11-01");
//Get todays date and format it
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
//This string will also need to be converted to a date object so the loop arithmetic can be performed.
String today = formatter.format(currentDate.getTime());
System.out.println(today);
for(String date: datesList) {
//The list cannot change from a list of strings.
//So the conversion will probably have to take place in this loop.
System.out.println(date);
//if(date < today) ...
//datesList.remove(date);
}
更新以包含解决方案:
List<String> datesList = new ArrayList<String>();
datesList.add("2013-11-01");
datesList.add("2011-11-01");
datesList.add("2013-04-29");
datesList.add("2001-05-19");
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
List<String> validDatesList = new ArrayList<String>();
for(String date: datesList) {
Date listItem = formatter.parse(date);
Date todayDate = new Date();
if(todayDate.after(listItem)) {
System.out.println(listItem+" has already happened because today is "+todayDate);
} else{
validDatesList.add(date);
}
}
for(String validDate: validDatesList) {
System.out.println("Valid date: "+validDate);
}
谢谢。