如何在 Android 中获取两个日期之间的所有日期。
例如。我有两个字符串。
String first="2012-07-15";
String second="2012-07-21";
我从这些字符串中转换并获取日期。
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("MMM dd");
String mydate = df2.format(df1.parse(first));
这样我就可以从第一个和第二个字符串中获取两个日期。
现在我还显示这两个日期之间的所有日期。
最佳答案
最好不要在日期计算中使用任何硬编码值。我们可以依靠 java Calendar
类方法来完成这个任务
看代码
private static List<Date> getDates(String dateString1, String dateString2)
{
ArrayList<Date> dates = new ArrayList<Date>();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = df1 .parse(dateString1);
date2 = df1 .parse(dateString2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while(!cal1.after(cal2))
{
dates.add(cal1.getTime());
cal1.add(Calendar.DATE, 1);
}
return dates;
}
并按如下方式使用它
List<Date> dates = getDates("2012-02-01", "2012-03-01");
for(Date date:dates)
System.out.println(date);
关于android - 在 Android 中生成两个日期之间的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11412713/