简体   繁体   中英

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

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());

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM