This question already has an answer here:
-
How to check if a date Object equals yesterday?
8 answers
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 ?
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);
I found org.apache.commons.lang3.time.DateUtils
is more intuitive and easy to use.
For your question
Date date = DateUtils.addDays(new Date(), -1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
will do the trick. And it works well also in JDK7 or below.
With Java 8 and later, use java.time.LocalDate
class:
LocalDate yesterday = LocalDate.now().minusDays(1L);
You can create a Date() object for "yesterday":
private static final String CURRENT_DATE_FORMAT = "yyyy-MM-dd";
public final static String format(Date date) {
DateFormat dateFormat = new SimpleDateFormat(CURRENT_DATE_FORMAT);
return dateFormat.format(date);
}
public final static String formatToday() {
return format(new Date());
}
public final static String formatYesterday() {
return format(new Date(new Date().getTime() - 24*3600*1000));
}
Try this:
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();
date .setTime(date.getTime()-24*60*60*1000); // Subtract 24*60*60*1000 milliseconds
return dateFormat.format(date);
}
}
Please Try This to get the Date of Yesterday:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long yourDateMillis = System.currentTimeMillis()- (24 * 60 * 60 * 1000);
Time yourDate = new Time();
yourDate.set(yourDateMillis);
String formattedDate = yourDate.format("%d-%m-%Y");
txtViewYesterday.setText(formattedDate);}