-2

Possible Duplicate:
Anyone know a simple way using java calendar to subtract X days to a date?

I d like to get a date string from newDate, and from days

so the yesterday day looks like this:

sdate="2011-07-11" 
days=-1

next day
sdate="2011-07-11" 
days=+1


public static String getNewDate(String sdate, int days) {

return "2011-07-10" or "2011-07-12"

how can i do this?

Community
  • 1
  • 1
lacas
  • 13,928
  • 30
  • 109
  • 183
  • 2
    Plenty of duplicates of this one. Have you taken a look at the related questions in the side bar? – Joey Jul 11 '11 at 12:46

4 Answers4

4

Use DateFormat and Calendar, like:

private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

public static String getNewDate(String sdate, int days) throws Exception {
    Date inputDate = dateFormat.parse(sdate);

    Calendar calendar = new GregorianCalendar();
    calendar.setTime(inputDate);
    calendar.add(Calendar.DAY_OF_MONTH, days);

    return dateFormat.format(calendar.getTime());
}

public static void main(String[] args) throws Exception {
    System.out.println(getNewDate("2011-07-11", -1));
    System.out.println(getNewDate("2011-07-11", 1));
}
aroth
  • 54,026
  • 20
  • 135
  • 176
2

Whats wrong with following ?

calendar.add(Calendar.DATE, noOfDaysToAdd);
jmj
  • 237,923
  • 42
  • 401
  • 438
1

How to subtract X days from a date using Java calendar?
adding days to a date

Community
  • 1
  • 1
zacheusz
  • 8,750
  • 3
  • 36
  • 60
0

If you really want to do date manipulation, I say you are better off working with java.util.Calendar (is really GregorianCalendar under the covers for almost every case).

Then if you want to convert it to String you can always use toString off it.

Chris Aldrich
  • 1,904
  • 1
  • 22
  • 37