I am using
DateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = new Date();
String fromdate = dateFormat.format(date);
to get the current date, how can I get the date 7 days back. For example, if today is 7th June 2013, how can I get 31th May 2013 in the same format as defined in date formatter?
Got the solution:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = new Date();
String todate = dateFormat.format(date);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
String fromdate = dateFormat.format(todate1);
For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.
Java now has a pretty good built-in date library, java.time bundled with Java 8.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Foo {
public static void main(String[] args) {
DateTimeFormatter format =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.minusDays(7);
System.out.println(String.format(
"Now: %s\nThen: %s",
now.format(format),
then.format(format)
));
/*
Example output:
Now: 2014-05-09T14:51:48Z
Then: 2014-05-02T14:51:48Z
*/
}
}
Or use JodaTime:
DateTime lastWeek = new DateTime().minusDays(7);
You can use this to continue using the type Date and a more legible code, if you preffer:
import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);
Use the Calendar-API:
// get Calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
// substract 7 days
// If we give 7 there it will give 8 days back
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-6);
// convert to date
Date myDate = cal.getTime();
Hope this helps. Have Fun!
Source: Stackoverflow.com