[java] Get yesterday's date using Date

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:


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


This question is related to java date datetime simpledateformat

The answer is


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

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


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


Similar questions with java tag:

Similar questions with date tag:

Similar questions with datetime tag:

Similar questions with simpledateformat tag: