Get Date of past 7days from current in android
android
Solution
Use `java.util.Calendar`, set it to today's date and then subtract 7 days.
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_YEAR, -7);
Date 7daysBeforeDate = cal.getTime();
Edit: In Java 8 it can be done much easier by using classes from `java.time` package:
final LocalDate date = LocalDate.now();
final LocalDate dateMinus7Days = date.minusDays(7);
//Format and display date
final String formattedDate = dateMinus7Days.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(formattedDate);
Problem
I am trying to fetch the date 7days prior to today's date. I am using SimpleDateFormat to fetch today's date. ``` SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); ``` Please guide me through this Updated answer which I found most useful ``` SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy"); String currentDateandTime = sdf.format(new Date()); Date cdate=sdf.parse(currentDateandTime); Calendar now2= Calendar.getInstance(); now2.add(Calendar.DATE, -7); String beforedate=now2.get(Calendar.DATE)+"/"+(now2.get(Calendar.MONTH) + 1)+"/"+now2.get(Calendar.YEAR); Date BeforeDate1=sdf.parse(beforedate); cdate.compareTo(BeforeDate1); ``` Thank you for you reply