Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the date 7 days earlier date from current date in Java [duplicate]

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?

Update

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); 
like image 717
Tanu Garg Avatar asked Jun 07 '13 10:06

Tanu Garg


People also ask

How do I add 7 days to Java Util date?

Adding Days to the given Date using Calendar class Add the given date to the calendar by using setTime() method of calendar class. Use the add() method of the calendar class to add days to the date. The add method() takes two parameter, i.e., calendar field and amount of time that needs to be added.

How can I get previous date in Java?

Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.

How do I subtract days from a date in Java?

The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31. This instance is immutable and unaffected by this method call.

How do you check if a date is before another date in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.


1 Answers

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.

like image 134
AllTooSir Avatar answered Oct 03 '22 04:10

AllTooSir