A Techie Writer's Block

Programming to go!

Getting yesterday’s Date in Java using the Calendar

Leave a comment

So yeah, there are other, easier ways of going around this in Java (e.g. Joda). However, there are times when your specifications tell you that you need to use older implementation methods to get the same result.

Anyway, one thing that bugs me is that it’s so easy to create and get today’s date in Java:

Date today = new Date();

But to get yesterday’s date, not so straightforward. To get it using Calendar, you have to do:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1); // number represents number of days
Date yesterday = cal.getTime();

System.out.println("Yesterday's date is: " + yesterday);

However, this is relative to your current time. That is, by default, the date will be shown together with the current timestamp when this bit is run. What if you want to set it to yesterday midnight?

Easy:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1); // number represents number of days

// set to midnight
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date yesterday = cal.getTime();

System.out.println("Yesterday's date is: " + yesterday);

Author: Lee

Just an ordinary software engineer who happens to have dabbled in a lot of different technologies over the years... :p

Leave a comment