如何从特定日期获取最近7天

How to fetch recent seven days from specific date

如果日期是 2017-03-30 我想获取从 2017-03-232017-03-30

的日期

我尝试使用此代码让我的 String 更改为 Date 格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Date dateParse = sdf.parse("2017-03-30");

然后我卡住了,因为我参考的是这样获取当前时间

Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -7);
//may be my dateParse should put here , but i don't know how to do
Date monday = c.getTime();//it get the current time
String preMonday = sdf.format(monday);

谁能教教我怎么取这7天?提前致谢。

解析日期:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = sdf.parse("2017-03-30");

第一个解决方案 1) 然后算出您需要减去多少毫秒:

Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000

第二种方案2)或者使用java.util.Calendar提供的API class:

Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();

然后,如果需要,将其转换回字符串:

String date = dateFormat.format(newDate);

此回答来自here

编辑: 如果您需要输出为 2017-03-29 2017-03-28 2017-03-27 ...... 2017-03-23 然后尝试下面的代码

for(int i = 1; i <= 7; i++){
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(myDate);
    calendar.add(Calendar.DAY_OF_YEAR, -i);
    Date newDate = calendar.getTime();
    String date = dateFormat.format(newDate);
    //here in date you can get all date from and output as 2017-03-29 2017-03-28 2017-03-27 ...... 2017-03-23
}

希望你需要这个

您可以使用下面的代码

  SimpleDateFormatdateFormat = new SimpleDateFormat("dd MMM yyyy");
        Calendar c = Calendar.getInstance();
       String date = dateFormat.format(c.getTime());

  c.add(Calendar.DATE, 7);
        String date1 = dateFormat.format(c.getTime());