Android: How to calculate a date some days ago?

Alex Fragotsis picture Alex Fragotsis · Oct 7, 2011 · Viewed 7.5k times · Source

I get the today's date like this:

final Calendar cal = Calendar.getInstance();
{
   mYear = cal.get(Calendar.YEAR);
   mMonth = cal.get(Calendar.MONTH);
   mDay = cal.get(Calendar.DAY_OF_MONTH);
}

I want to calculate what was the date x days ago... anyone got something?

Answer

Jan Korpegård picture Jan Korpegård · Oct 7, 2011

A better way would be to use add method instead of set:

cal.add(DAY_OF_YEAR, -2);

I.e. to be sure it works also the first day in month etc.