user
user

Reputation: 121

Calculate with date in Android

Does anyone here know what the best way is to calculate the date 2 days in the past?

I've got this piece of code to retrieve the current date:

public static String getDateTime (String Format){
    SimpleDateFormat sdf = new SimpleDateFormat(Format);
    return sdf.format(new Date());
}

But I want to be able to calculate the date 2 days in the past. So decrease the date with 2 days. Anyone who knows what the best way is to do this?

Thanks in advance

Upvotes: 0

Views: 1239

Answers (2)

Neil Townsend
Neil Townsend

Reputation: 6084

Using Calendar is probably the easiest way. Assuming that you have defined Format as per the question:

// get Now
Calendar cal = Calendar.getInstance();

// go back two days
cal.add(Calendar.DAY_OF_YEAR, -2);

// display
SimpleDateFormat sdf = new SimpleDateFormat(Format);
String string = sdf.format(cal.getTime());

Upvotes: 3

Christophe Longeanie
Christophe Longeanie

Reputation: 430

Just use Calendar's add() function:

Calendar c = Calendar.getInstance();
c.setTime(yourDateObject);
c.add(Calendar.DAY_OF_MONTH, -2);

It will automatically change the month, year, etc. if necessary.

Upvotes: 0

Related Questions