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

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);

This question is related to java date datetime

The answer is


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!


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?