Get date in past using java.util.Date

you could manipulate a date with Calendar's methods.

DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = new Date(System.currentTimeMillis());
System.out.println("result is "+ dateFormat.format(myDate));
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DATE, -10);
System.out.println(dateFormat.format(cal.getTime()));

This line

Date oneDayBefore = new Date(myDate.getTime() - 10);    

sets the date back 10 milliseconds, not 10 days. The easiest solution would be to just subtract the number of milliseconds in 10 days:

Date tenDaysBefore = new Date(myDate.getTime() - (10 * 24 * 60 * 60 * 1000));    

Use Calendar.add(Calendar.DAY_OF_MONTH, -10).

Tags:

Java