15

I am assuming Java has some built-in way to do this.

Given a date, how can I determine the date one day prior to that date?

For example, suppose I am given 3/1/2009. The previous date is 2/28/2009. If I had been given 3/1/2008, the previous date would have been 2/29/2008.

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
William Brendel
  • 31,712
  • 14
  • 72
  • 77

8 Answers8

47

Use the Calendar interface.

Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DAY_OF_YEAR,-1);
Date oneDayBefore= cal.getTime();

Doing "addition" in this way guarantees you get a valid date. This is valid for 1st of the year as well, e.g. if myDate is January 1st, 2012, oneDayBefore will be December 31st, 2011.

Mike Pone
  • 18,705
  • 13
  • 53
  • 68
  • 1
    Btw, `Calendar.getInstance()` would probably be a bit more generic way to achieve the instance of Calendar. – LoKi Nov 07 '13 at 14:42
8

You can also use Joda-Time, a very good Java library to manipulate dates:

DateTime result = dt.minusDays(1);
Vladimir
  • 6,853
  • 2
  • 26
  • 25
5

With java.time.Instant

Date.from(Instant.now().minus(Duration.ofDays(1)))
Vincnetas
  • 146
  • 1
  • 4
4

The java.util.Calendar class allows us to add or subtract any number of day/weeks/months/whatever from a date. Just use the add() method:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html

Example:

Calendar date = new GregorianCalendar(2009, 3, 1);
date.add(Calendar.DATE, -1);
moinudin
  • 134,091
  • 45
  • 190
  • 216
1

This would help.

getPreviousDateForGivenDate("2015-01-19", 10);
getPreviousDateForGivenDate("2015-01-19", -10);

public static String getPreviousDateForGivenDate(String givenDate, int datesPriorOrAfter) {
    String saleDate = getPreviousDate(datesPriorOrAfter);

    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] arr = givenDate.split("-", 3);
        Calendar cal = new GregorianCalendar(Integer.parseInt(arr[0]), Integer.parseInt(arr[1])-1, Integer.parseInt(arr[2]));
        cal.add(Calendar.DAY_OF_YEAR, datesPriorOrAfter);    
        saleDate = dateFormat.format(cal.getTime());

    } catch (Exception e) {
        System.out.println("Error at getPreviousDateForGivenDate():"+e.getMessage());
    }

    return saleDate;
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Vimalraj
  • 11
  • 1
1

With the date4j library :

DateTime yesterday = today.minusDays(1);
John
  • 1,635
  • 15
  • 22
1

java.time

The java.time API introduced with Java-8 (March 2014) supplants the error-prone and outdated java.util and their formatting API, SimpleDateFormat. It is recommended to stop using the legacy date-time API and switch to the modern date-time API.

How to parse a date string using java.time API?

Use LocalDate#parse(CharSequence text, DateTimeFormatter formatter) to parse a date string which is not in ISO 8601 format. However, a date string already in ISO 8601 format (yyyy-MM-dd), can be parsed using LocalDate parse(CharSequence text).

Demo:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
        String strDateTime = "3/1/2009";
        LocalDate date = LocalDate.parse(strDateTime, formatter);
        System.out.println(date);

        strDateTime = "2009-03-01";
        date = LocalDate.parse(strDateTime);
        System.out.println(date);
    }
}

Output:

2009-03-01
2009-03-01

How to get the previous date using java.time API?

The simplest option is to use LocalDate#minusDays. You can use one of the overloaded LocalDate#minus functions as well but they are there mainly to subtract for other time units e.g. hour, minute etc.

Demo:

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println(today);
        LocalDate previousDay = today.minusDays(1);
        System.out.println(previousDay);

        // Alternatively
        previousDay = today.minus(Period.ofDays(1));
        System.out.println(previousDay);

        // Alternatively
        previousDay = today.minus(1, ChronoUnit.DAYS);
        System.out.println(previousDay);
    }
}

Output:

2022-10-13
2022-10-12
2022-10-12
2022-10-12

Putting together:

LocalDate previousDay = LocalDate.parse(
                            "3/1/2009", 
                            DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH)
                        ).minusDays(1); // 2009-02-28

Just in case

Just in case, you want the result to be formatted in the same format as the date string, use DateTimeFormatter#format e.g.

DateTimeFormatter formatter= DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
System.out.println(previousDay.format(formatter)); // 2/28/2009

// Alternatively
System.out.println(formatter.format(previousDay)); // 2/28/2009

Learn more about the the modern date-time API from Trail: Date Time.

Some useful links:

  1. Never use Date-Time formatting/parsing API without a Locale
  2. I prefer u to y with DateTimeFormatter.
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;


public class TestDayBefore {

    public static void main(String... args) {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.set(YEAR, 2009);
        calendar.set(MONTH, MARCH);
        calendar.set(DAY_OF_MONTH, 1);
        System.out.println(calendar.getTime()); //prints Sun Mar 01 23:20:20 EET 2009
        calendar.add(DAY_OF_MONTH, -1);
        System.out.println(calendar.getTime()); //prints Sat Feb 28 23:21:01 EET 2009

    }
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
MahdeTo
  • 11,034
  • 2
  • 27
  • 28