How can I get yesterday's date without using Calendar in Java and without a timestamp just the date?

wheelerlc64 picture wheelerlc64 · Mar 17, 2014 · Viewed 53.1k times · Source

I have wrote a method to get the current date in the format of yyyy-MM-dd and want to be able to also create another method for getting yesterday's date, the day before the current date. All this needs is the date and not the timestamp. I am not trying to use Calendar as well. I have set up the current date this way:

public class DateWithNoTimestamp
{
       private static final String CURRENT_DATE_FORMAT = "yyyy-MM-dd";

       public final static String getCurrentDate()
       {
               DateFormat dateFormat = new SimpleDateFormat(CURRENT_DATE_FORMAT);
               Date date = new Date();
               return dateFormat.format(date);
       } 
}

This works to get the current date, now the separate method getYesertdayDate() I'm having trouble with. How can I set it up in a similar way as I did with getCurrentDate() while subtracting one day ?

Answer

Giovanni Botta picture Giovanni Botta · Mar 17, 2014

You could simply subtract 1000 * 60 * 60 * 24 milliseconds from the date and format that value:

Date yesterday = new Date(System.currentTimeMillis() - 1000L * 60L * 60L * 24L));

That's the quick-and-dirty way, and, as noted in the comments, it might break when daylight savings transitions happen (two days per year). Recommended alternatives are the Calendar API, the Joda API or the new JDK 8 time API:

LocalDate today = LocalDate.now();
LocalDate yesterday = today.minusDays(1);