开发者

Java getDate date-x days [duplicate]

This question already has answers here: Closed 11 years ago.

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 Stri开发者_运维百科ng getNewDate(String sdate, int days) {

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

how can i do this?


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


Whats wrong with following ?

calendar.add(Calendar.DATE, noOfDaysToAdd);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜