Get yesterday's date using Date

AKIWEB picture AKIWEB · Jul 11, 2012 · Viewed 303k times · Source

The following function produces today's date; how can I make it produce only yesterday's date?

private String toDate() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();    
        return dateFormat.format(date).toString();
}

This is the output:

2012-07-10

I only need yesterday's date like below. Is it possible to do this in my function?

2012-07-09

Answer

Jigar Joshi picture Jigar Joshi · Jul 11, 2012

Update

There has been recent improvements in datetime API with JSR-310.

Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);

https://ideone.com/91M1eU

Outdated answer

You are subtracting the wrong number:

Use Calendar instead:

private Date yesterday() {
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1);
    return cal.getTime();
}

Then, modify your method to the following:

private String getYesterdayDateString() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return dateFormat.format(yesterday());
}

See