Explain Codes LogoExplain Codes Logo

Get yesterday's date using Date

java
date-formatting
java-8
calendar-api
Nikita BarsukovbyNikita Barsukov·Dec 23, 2024
TLDR

Here's a nifty way to obtain yesterday's date using Calendar in Java:

Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); // Make time travel possible Date yesterday = cal.getTime();

In three lines of code, we go from today to yesterday—no Delorean required.

Mind the time zone

Time zones matter. Today in New York might be yesterday in Sydney. So, when handling dates, consider the user's time zone:

TimeZone tz = TimeZone.getDefault(); // Home sweet home Calendar cal = Calendar.getInstance(tz); cal.add(Calendar.DATE, -1); // One small step back… Date yesterday = cal.getTime(); // …a giant leap to yesterday

The code treats calendar.getInstance(tz) as local time, ensuring that "yesterday" is truly yesterday for the user.

Modernizing with java.time

Java 8 introduced the java.time package, offering a more elegant approach:

LocalDate yesterday = LocalDate.now().minusDays(1); // Apple dropping “Mac” from MacBook

This gets yesterday's date quicker than you can say "Deprecated!"

Date formatting with SimpleDateFormat

String out a date in a pretty pattern using SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // My kind of grammar Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); // Walking down memory lane String formattedDate = sdf.format(cal.getTime()); // Polished to perfection

Here, we dress yesterday's date in the user-friendly "yyyy-MM-dd" format.

Edge cases - the odd ones out

Expect the unexpected. Edge cases like leap years and month starts might throw a spanner in the works:

Calendar cal = Calendar.getInstance(); if (cal.get(Calendar.DAY_OF_MONTH) == 1) { // Is it the first? cal.add(Calendar.MONTH, -1); // Go back, way back cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); } else { cal.add(Calendar.DATE, -1); // Usual drill } Date yesterday = cal.getTime(); // Foolproof yesterday!

This concoction ensures yesterday's date remains consistent, even on edge cases.

A maintainable and updatable solution

Future-proof your code. Encapsulating logic in a dynamic function ensures your solution stands the test of time:

public static Date getYesterday() { Calendar cal = Calendar.getInstance(TimeZone.getDefault()); // Local time cal.add(Calendar.DATE, -1); // Yesterday, all my troubles seemed so far away… return cal.getTime(); }

It's flexible, maintainable, and understandable, just like a great haircut.

The power of milliseconds

Tap into the precise and rich world of milliseconds for date calculation:

long millisInADay = 86_400_000L; // That's a long wait Date yesterday = new Date(System.currentTimeMillis() - millisInADay); // Feels shorter this way

You've now surfed from the current time back to yesterday on a wave of milliseconds.

Resources for hands-on experiences

If you prefer seeing code in action, the IDEOne Demo helps you visualize date calculations in a real-world context.