Morton
Morton

Reputation: 5782

How to fetch recent seven days from specific date

If the date is 2017-03-30 that i want to fetch the date from 2017-03-23 to 2017-03-30

I try to use this code let my String change to Date format

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

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

then i'm stuck , cause i take the reference is get the current time like this

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);

Is any one can teach me how to fetch these seven days ? Thanks in advance.

Upvotes: 0

Views: 260

Answers (2)

Zaki Pathan
Zaki Pathan

Reputation: 1782

Parse the date:

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

First Solution 1) And then either figure out how many milliseconds you need to subtract:

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

Second Solution 2) Or use the API provided by the java.util.Calendar class:

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

Then, if you need to, convert it back to a String:

String date = dateFormat.format(newDate);

This answer is from here

EDIT: If you need output as 2017-03-29 2017-03-28 2017-03-27 ...... 2017-03-23 then try below code

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
}

Hope you need this

Upvotes: 1

Deepali-Systematix
Deepali-Systematix

Reputation: 168

You can use the code below

  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());

Upvotes: 2

Related Questions