Getting dates through code yesterday

I am using the following code to get today's date.

Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
return dateFormat.format(cal.getTime());

But I also want yesteday date to be in the same format.

I use

        Calendar cal = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    cal.add(Calendar.DATE, -1);
    return dateFormat.format(cal.getTime());

but I feel that it will work after changing the month or year. How can i solve this. Help is greatly appreciated.

+3
source share
4 answers

I don’t think so .. what date is, she should get it and subtract it ... and return the date of the day earlier. This is what this function should perform.

+1
source

I would do the following:

Date d = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.format(d);
+8
source

?

+2

:

cal.set(year, month , day);
long lastDay = cal.getTimeInMillis() - (24 * 60 * 60 * 1000);
cal.setTimeInMillis(lastDay);

!

0

Source: https://habr.com/ru/post/1794944/


All Articles