Avoid java.util.Date and .Calendar
The answer is accepted correctly. However, the java.util.Date and .Calendar classes are notoriously unpleasant. Avoid them. Use Joda-Time or the new java.time package (in Java 8).
Separate manipulation of time dates from formatting
In addition, the code in the question mixes date-time with formatting. Separate these tasks to make your code clean and testing / debugging easier.
Timezone
The time zone is critical for working with a date. If you ignore the problem, the default JVM time zone will be applied. Best practice is to always indicate, not rely on default. Even if you want the default, explicitly call getDefault .
The start of the day is determined by the time zone. A new day comes earlier in Paris than in Montreal. Therefore, if βyesterdayβ you mean the first moment of this day, then you must (a) specify the time zone and (b) call withTimeAtStartOfDay .
Joda time
Sample code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); DateTime today = DateTime.now( timeZone );
Or convert from java.util.Date object.
DateTime today = new DateTime( myJUDate, timeZone );
Subtract the day to get to yesterday (or the day before).
DateTime yesterday = today.minusDays( 1 ); DateTime yesterdayStartOfDay = today.minusDays( 1 ).withTimeAtStartOfDay();
By default, Joda-Time and java.time parse / generate strings in ISO 8601 format .
String output = yesterdayStartOfDay.toString(); // Uses ISO 8601 format by default.
Use the formatter for the full date as a four-digit year, a two-digit month of the year, and a two-digit day of the month (yyyy-MM-dd). Such a formatter is already defined in Yoda-Time.
String outputDatePortion = ISODateFormat.date().print( yesterdayStartOfDay );