Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 342
wheelerlc64 Avatar asked Mar 17 '14 15:03

wheelerlc64


People also ask

How can I get current date without timestamp?

Using Calendar. One of the most common ways to get a Date without time is to use the Calendar class to set the time to zero. By doing this we get a clean date, with the time set at the start of the day.

How do I find yesterday's date?

How do you get yesterdays' date using JavaScript? We use the setDate() method on yesterday , passing as parameter the current day minus one. Even if it's day 1 of the month, JavaScript is logical enough and it will point to the last day of the previous month.


1 Answers

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); 
like image 111
Giovanni Botta Avatar answered Oct 19 '22 22:10

Giovanni Botta