Core Java

Getting Yesterday’s Date in Java

Hello. In this tutorial, we will be Getting Yesterday’s Date in Java by exploring various methods.

1. Introduction

In Java, you can use the following methods to obtain the previous day’s date.

1.1 Using the java.util.Calendar class

The java.util.Calendar class is a part of the Java standard library and provides functionality for working with dates and times. It allows you to perform various operations such as getting and setting different components of a date, manipulating dates, and performing calculations.

Here’s an example that demonstrates the usage of java.util.Calendar to obtain yesterday’s date:

Example 1

import java.util.Calendar;

public class YesterdayDateExample {
    public static void main(String[] args) {
        // Get today's date
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        
        // Extract year, month, and day
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // Month is zero-based
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        
        // Print yesterday's date
        System.out.println("Yesterday's date: " + year + "-" + month + "-" + day);
    }
}

1.1.1 Explanation of the code

In this example, we first obtain an instance of the Calendar class using the Calendar.getInstance() method, which returns a Calendar object initialized with the current date and time. We then use the add() method to subtract one day from the current date by specifying Calendar.DAY_OF_YEAR as the field to modify and -1 as the amount to subtract.

Next, we use the get() method to extract the year, month, and day components from the Calendar object. Note that the month is zero-based, so we add 1 to it to get the correct month value.

Finally, we print the extracted components to obtain yesterday’s date in the format “YYYY-MM-DD” using string concatenation.

When you run this code, it will display yesterday’s date. For example, if today is July 18, 2023, the output will be:

Fig. 1: Using the java.util.Calendar class.
Fig. 1: Using the java.util.Calendar class.

1.2 Using the java.time.LocalDate class

In this example, we first obtain an instance of the LocalDate class using the LocalDate.now() method, which returns the current date. We then use the minusDays() method to subtract one day from the current date and store the result in the yesterday variable.

Example 2

import java.time.LocalDate;

public class YesterdayDateExample {
    public static void main(String[] args) {
        // Get today's date
        LocalDate today = LocalDate.now();
        
        // Subtract one day to get yesterday's date
        LocalDate yesterday = today.minusDays(1);
        
        // Print yesterday's date
        System.out.println("Yesterday's date: " + yesterday);
    }
}

1.2.1 Explanation of the code

In this example, we import the java.time.LocalDate class to use the date-related functionality provided by the java.time package. We then call the now() method on LocalDate to obtain today’s date. After that, we use the minusDays() method to subtract one day from the current date and assign the result to the yesterday variable. Finally, we print the value of yesterday using System.out.println() to obtain yesterday’s date.

When you run this code, it will display yesterday’s date. For example, if today is 2023-07-18, the output will be:

Fig. 2: Using the java.time.LocalDate class.
Fig. 2: Using the java.time.LocalDate class.

1.3 Using the java.util.Date class

In this example, we first obtain the current date using the Date() constructor from the java.util.Date class. We then subtract one day from the current date using the setTime() and getTime() methods.

Example 3

import java.util.Date;

public class YesterdayDateExample {
    public static void main(String[] args) {
        // Get today's date
        Date today = new Date();
        
        // Subtract one day to get yesterday's date
        long oneDayInMillis = 24 * 60 * 60 * 1000;
        Date yesterday = new Date(today.getTime() - oneDayInMillis);
        
        // Print yesterday's date
        System.out.println("Yesterday's date: " + yesterday);
    }
}

1.3.1 Explanation of the code

In this example, we import the java.util.Date class to work with dates. We create an instance of Date using the Date() constructor, which initializes it with the current date and time.

To obtain yesterday’s date, we calculate the number of milliseconds in a day (24 hours) and subtract that value from the current date’s time using today.getTime() - oneDayInMillis. This gives us the timestamp for yesterday. We then create a new Date object with this timestamp.

Finally, we print the value of yesterday using System.out.println() to obtain yesterday’s date.

When you run this code, it will display yesterday’s date. For example, if today is July 18, 2023, the output will be:

Fig. 3: Using the java.util.Date class.
Fig. 3: Using the java.util.Date class.

1.4 Using the java.time.LocalDateTime class

In this example, we first obtain the current date and time using the LocalDateTime.now() method from the java.time.LocalDateTime class. We then subtract one day from the current date and time using the minusDays() method.

Example 4

import java.time.LocalDateTime;

public class YesterdayDateExample {
    public static void main(String[] args) {
        // Get current date and time
        LocalDateTime currentDateTime = LocalDateTime.now();
        
        // Subtract one day to get yesterday's date and time
        LocalDateTime yesterday = currentDateTime.minusDays(1);
        
        // Print yesterday's date and time
        System.out.println("Yesterday's date and time: " + yesterday);
    }
}

1.4.1 Explanation of the code

In this example, we import the java.time.LocalDateTime class to work with date and time values. We use the now() method on LocalDateTime to obtain the current date and time.

To obtain yesterday’s date and time, we call the minusDays() method on currentDateTime, subtracting one day from it. The result is stored in the yesterday variable.

Finally, we print the value of yesterday using System.out.println() to obtain yesterday’s date and time.

When you run this code, it will display yesterday’s date and time. For example, if the current date and time are 2023-07-18T12:34:56, the output will be:

Fig. 4: Using the java.time.LocalDateTime class.
Fig. 4: Using the java.time.LocalDateTime class.

1.5 Using the java.sql.Date class

In this example, we first obtain the current date using the java.util.Date class. We then create a new instance of the java.sql.Date class, passing the current date’s time in milliseconds as a constructor argument.

Example 5

import java.util.Date;
import java.sql.Date;

public class YesterdayDateExample {
    public static void main(String[] args) {
        // Get current date
        Date currentDate = new Date();
        
        // Create java.sql.Date instance with current date's time in milliseconds
        Date currentSqlDate = new Date(currentDate.getTime());
        
        // Subtract one day to get yesterday's date
        long oneDayInMillis = 24 * 60 * 60 * 1000;
        Date yesterdaySqlDate = new Date(currentSqlDate.getTime() - oneDayInMillis);
        
        // Print yesterday's date
        System.out.println("Yesterday's date: " + yesterdaySqlDate);
    }
}

1.5.1 Explanation of the code

In this example, we import the java.util.Date and java.sql.Date classes. We create an instance of Date using the Date() constructor, which initializes it with the current date and time.

To obtain yesterday’s date, we calculate the number of milliseconds in a day (24 hours) and subtract that value from the current date’s time using currentSqlDate.getTime() - oneDayInMillis. This gives us the timestamp for yesterday. We then create a new java.sql.Date object with this timestamp.

Finally, we print the value of yesterdaySqlDate using System.out.println() to obtain yesterday’s date.

When you run this code, it will display yesterday’s date. For example, if today is July 18, 2023, the output will be:

Fig. 5: Using the java.sql.Date class.
Fig. 5: Using the java.sql.Date class.

2. Comparison between different approaches

ApproachClassAdvantagesDisadvantages
Using java.util.Calendarjava.util.Calendar
  • Provides flexibility for date manipulation.
  • Can handle more advanced date operations.
  • Requires more code compared to newer alternatives.
  • Uses a mutable class that is not thread-safe.
Using java.time.LocalDatejava.time.LocalDate
  • Clean and modern API for working with dates.
  • Easy to obtain yesterday’s date using the now() and minusDays() methods.
  • Immutable and thread-safe.
  • Requires Java 8 or newer.
Using java.util.Datejava.util.Date
  • Available in older versions of Java.
  • Compatible with legacy code.
  • Lacks modern date and time functionality.
  • Mutable and not thread-safe.
Using java.time.LocalDateTimejava.time.LocalDateTime
  • Provides date and time together in a single class.
  • Flexible for working with both date and time components.
  • Requires Java 8 or newer.
Using java.sql.Datejava.sql.Date
  • Used for compatibility with databases that require java.sql.Date.
  • Can be converted from java.util.Date if necessary.
  • Lacks modern date and time functionality.
  • Requires additional conversion steps in some cases.

This concludes our tutorial, and I trust that the article provided you with the information you sought. I wish you happy learning and encourage you to share your newfound knowledge with others!

3. Conclusion

In conclusion, we have explored various approaches to obtain yesterday’s date in Java using different date and time classes. Let’s summarize the different scenarios and their corresponding classes:

3.1 Using java.time.LocalDate

  • This is the recommended approach if you are using Java 8 or newer.
  • By using the LocalDate class and its now() and minusDays() methods, we can easily obtain yesterday’s date.
  • This approach provides a clean and modern API for working with dates.

3.2 Using java.util.Calendar

  • The Calendar class is a part of the Java standard library and provides more flexibility for date manipulation.
  • We can obtain an instance of Calendar using the getInstance() method and then use the add() and get() methods to subtract one day and extract date components.
  • This approach is suitable if you need more advanced date manipulation or if you are working with legacy code.

3.3 Using java.util.Date and java.sql.Date

  • The java.util.Date class is available in older versions of Java, but it lacks some modern date and time functionality.
  • We can create a Date object representing the current date using its constructor and then convert it to a java.sql.Date object if needed.
  • By subtracting the number of milliseconds in a day from the current date’s time, we can obtain yesterday’s date.
  • This approach may be necessary if you are working with older code or interacting with a database that requires java.sql.Date.

It’s worth noting that the java.time package introduced in Java 8 provides a more robust and user-friendly API for date and time operations. If possible, it is recommended to use the java.time.LocalDate class for obtaining yesterday’s date. However, in scenarios where you have constraints or compatibility requirements, the other approaches use java.util.Calendar, java.util.Date, or java.sql.Date can be used accordingly.

Remember to consider the version of Java you are using and the specific requirements of your project when choosing the appropriate date and time class.

You can download the source code from the Downloads section.

4. Download the Files

This was a tutorial on exploring different ways to find the previous day’s date in Java programming.

Download
You can download the files of this example here: Getting Yesterday’s Date in Java

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button