You can use Calendar class :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
System.out.println("Date = "+ cal.getTime());
But as @Sean Patrick Floyd mentioned , Joda-time is the best Java library for Date.
Answer from AllTooSir on Stack OverflowYou can use Calendar class :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
System.out.println("Date = "+ cal.getTime());
But as @Sean Patrick Floyd mentioned , Joda-time is the best Java library for Date.
Or use JodaTime:
DateTime lastWeek = new DateTime().minusDays(7);
add(Calendar.DAY_OF_MONTH, 7);
From Calendar JavaDoc
Calendar's add method does this for you:
cal.add(Calendar.DATE, 7);
EDIT:
Given the extended comments, I guess I should add to this by saying that if cal begins as October 4, 2011, and I call cal.add(Calendar.DATE, 7) the new value of cal is October 11, 2011. Similarly, if cal begins as March 29, 2025, then after cal.add(Calendar.DATE, 7) the new value of cal is April 5, 2025.
From exactly now:
long DAY_IN_MS = 1000 * 60 * 60 * 24;
new Date(System.currentTimeMillis() - (7 * DAY_IN_MS))
From arbitrary Date date:
new Date(date.getTime() - (7 * DAY_IN_MS))
Edit: As pointed out in the other answers, does not account for daylight savings time, if that's a factor.
Just to clarify that limitation I was talking about:
For people affected by daylight savings time, if by 7 days earlier, you mean that if right now is 12pm noon on 14 Mar 2010, you want the calculation of 7 days earlier to result in 12pm on 7 Mar 2010, then be careful.
This solution finds the date/time exactly 24 hours * 7 days= 168 hours earlier.
However, some people are surprised when this solution finds that, for example, (14 Mar 2010 1:00pm) - 7 * DAY_IN_MS may return a result in(7 Mar 2010 12:00pm) where the wall-clock time in your timezone isn't the same between the 2 date/times (1pm vs 12pm). This is due to daylight savings time starting or ending that night and the "wall-clock time" losing or gaining an hour.
If DST isn't a factor for you or if you really do want (168 hours) exactly (regardless of the shift in wall-clock time), then this solution works fine.
Otherwise, you may need to compensate for when your 7 days earlier doesn't really mean exactly 168 hours (due to DST starting or ending within that timeframe).
Use Calendar's facility to create new Date objects using getTime():
import java.util.GregorianCalendar;
import java.util.Date;
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_MONTH, -7);
Date sevenDaysAgo = cal.getTime();
LocalDate is perfect for this job:
LocalDate.now().plusDays(7);
You can get your string representation with
.format(DateTimeFormatter.ISO_DATE);
If you're not able to use Java 8, then you have a few options:
Use the ThreeTen-Backport, which backports most functionality of the Java 8 JSR-310 API, normally available in the
java.timepackage. See here for details. This package is available in Maven Central.You can also use Joda Time. The peculiar thing is that these two projects have almost the same layout of their websites.
If you're otherwise not able to use ThreeTen-Backport or Joda Time, you can use this:
Calendar c = GregorianCalendar.getInstance(); c.add(Calendar.DATE, 7); String s = new SimpleDateFormat("yyyy-MM-dd") .format(c.getTime());Warning
Many things are wrong with the old Date and Time API, see here. Use this only if you have no other option.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 7);
Date defaultEndDate = cal.getTime();
Using the java.time classes built into Java 8 and later:
LocalDate from = LocalDate.parse("2015-05-01");
LocalDate to = LocalDate.parse("2015-05-07");
long days = ChronoUnit.DAYS.between(from, to); // 6 days
long weeks = ChronoUnit.WEEKS.between(from, to); // 0 weeks
The easiest way is to use Jodatime and use
Days.daysBetween(start, end).getDays()
Another solution is to use Calendar, add 7 days and compare again.
Calendar c=Calendar.getInstance();
c.setTime(fromDate);
c.add(Calendar.DATE,7);
if(c.getTime().compareTo(toDate)<0){
It's more than 7 days.
}
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 7); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
took from this thread
How can I increment a date by one day in Java?
You leave your code exactly how it is and just remove your set call. When you call getInstance for a calendar you will get back a calendar instance that is set to the current date and time.
Ex:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar date = Calendar.getInstance();
for(int i = 0; i < 7;i++){
Calendar[i] = format.format(date.getTime());
date.add(Calendar.DATE , 1);
System.out.println("date :" + Calendar[i]);
}
Parse the date:
Date myDate = dateFormat.parse(dateString);
And then either figure out how many milliseconds you need to subtract:
Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000
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);
I have created my own function that may helpful to get Next/Previous date from
Current Date:
/**
* Pass your date format and no of days for minus from current
* If you want to get previous date then pass days with minus sign
* else you can pass as it is for next date
* @param dateFormat
* @param days
* @return Calculated Date
*/
public static String getCalculatedDate(String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
return s.format(new Date(cal.getTimeInMillis()));
}
Example:
getCalculatedDate("dd-MM-yyyy", -10); // It will gives you date before 10 days from current date
getCalculatedDate("dd-MM-yyyy", 10); // It will gives you date after 10 days from current date
and if you want to get Calculated Date with passing Your own date:
public static String getCalculatedDate(String date, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
try {
return s.format(new Date(s.parse(date).getTime()));
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.e("TAG", "Error in Parsing Date : " + e.getMessage());
}
return null;
}
Example with Passing own date:
getCalculatedDate("01-01-2015", "dd-MM-yyyy", -10); // It will gives you date before 10 days from given date
getCalculatedDate("01-01-2015", "dd-MM-yyyy", 10); // It will gives you date after 10 days from given date
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
@JigarJoshi it's the good answer, and of course also @Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);