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);
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.
Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With