在我的应用中,我需要从当天开始的七天。 我尝试了以下解决方案,但它正在跳过几天。
Calendar calendar = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
for (int i = 0; i < 7; i++) {
calendar.add(Calendar.DATE, i);
String day = sdf.format(calendar.getTime());
Log.i(TAG, day);
}
我得到以下输出:
Sunday 18-Oct-2015
Monday 19-Oct-2015
Wednesday 21-Oct-2015
Saturday 24-Oct-2015
Wednesday 28-Oct-2015
Monday 02-Nov-2015
Sunday 08-Nov-2015
我还尝试了Calendar.DAY_OF_WEEK
,Calendar.DAY_OF_MONTH
,Calendar.DAY_OF_YEAR
而不是Calendar.DATE
,但获得了相同的输出。
答案 0 :(得分:16)
试试这个:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
for (int i = 0; i < 7; i++) {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.DATE, i);
String day = sdf.format(calendar.getTime());
Log.i(TAG, day);
}
您有一个日历实例,并且正在添加1,2,3,4,5,6和7天而不重置它。上述解决方案将对象创建移动到循环内。
答案 1 :(得分:1)
使用Java 8+找到了最简单的方法
plusDays
final LocalDate date = LocalDate.now();
final LocalDate plusDays = date.plusDays(7);
//if you want to show past 7 days, change to data.minusDays(7);
final String formattedDate = plusDays.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")); // show is this format 09/30/2020
System.out.println(formattedDate); //09/30/2020
MinusDays
final LocalDate date = LocalDate.now();
final LocalDate minusDays = date.minusDays(7);
final String formattedDate = minusDays.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
System.out.println(formattedDate);
dateTimeFormat里面有很多功能,请参阅 https://howtodoinjava.com/java/date-time/java8-datetimeformatter-example/