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 ?
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 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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With