如何从java中的特定日期获取前7个日期?我从当前日期获得7个日期,但我想从特定日期开始
问题描述:
//explain
public class DateLoop {
static String finalDate;
static String particularDate;
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat("d-M-yyyy ");
Calendar cal = Calendar.getInstance();
particularDate = "2-1-2018";
// get starting date
cal.add(Calendar.DAY_OF_YEAR, -7);
// loop adding one day in each iteration
for(int i = 0; i< 7; i++){
cal.add(Calendar.DAY_OF_YEAR, 1);
finalDate =sdf.format(cal.getTime());
System.out.println(finalDate);
//ie, its giving previous 7 dates from present date, but I want
//particular date... thanks in advance
}
}
}
即,它从现在的日期开始提供前7个日期,但我想要前7个日期来自特定日期。
ie, its giving previous 7 dates from present date, but I want previous 7 dates from particular date.
答
tl; dr
tl;dr
LocalDate.of( 2018 , Month.JANUARY , 23 )
.minusDays( … )
java.time
您正在使用现在遗留下来的麻烦的旧日期时间类,取而代之的是 java.time 类。
使用 LocalDate
仅限日期,没有时间。
Use LocalDate
for a date-only without time-of-day.
使用月
枚举。
LocalDate start = LocalDate.of( 2018 , Month.JANUARY , 23 ) ; // 2018-01-23.
使用月份数,1月至12月为1-12。
Using month numbers, 1-12 for January-December.
LocalDate start = LocalDate.of( 2018 , 1 , 23 ) ; // 2018-01-23.
收集一系列日期。
List<LocalDate> dates = new ArrayList<>( 7 ) ;
for( int i = 1 ; i <= 7 ; i ++ ) {
LocalDate ld = start.minusDays( i ) ; // Determine previous date.
dates.add( ld ) ; // Add that date object to the list.
}
对于早期的Android,请使用 ThreeTen-Backport 和 ThreeTenABP 项目。
For earlier Android, use the ThreeTen-Backport and ThreeTenABP projects.