How to Get Previous Day in Java

1. Introduction

Calculating the previous day from a given date is a common requirement in many applications, such as logging, reporting, and historical data retrieval. Java's java.time.LocalDate class provides methods to easily manipulate dates, including moving backwards in time.

Key Points

1. LocalDate represents a date with no time of day or timezone.

2. The minusDays method is used to subtract days from a given date.

3. This functionality is essential for date-based calculations and adjustments.

2. Program Steps

1. Import the LocalDate class.

2. Get the current date.

3. Subtract one day to get the previous day.

3. Code Program

import java.time.LocalDate;

public class PreviousDayFinder {

    public static void main(String[] args) {
        // Step 2: Get the current date
        LocalDate today = LocalDate.now();

        // Step 3: Subtract one day to find the previous day
        LocalDate yesterday = today.minusDays(1);

        // Print the result
        System.out.println("Yesterday was: " + yesterday);
    }
}

Output:

Yesterday was: 2023-10-02  // Output will vary based on the current date

Explanation:

1. LocalDate.now() is used to obtain the current date according to the system clock in the default time-zone.

2. today.minusDays(1) subtracts one day from the current date, yielding the previous day. This method is straightforward and avoids the complexity of manual date calculations.

3. The result is stored in yesterday and printed, providing a clear indication of what the date was the day before today. This method is crucial for applications that need to process or display data from the day before the current day.


Comments