Adding Days to Calendar

自作多情 提交于 2019-11-30 19:43:53

There's too much code here. Too much user interaction.

Start with a simple method to do one thing, then work your way out after you get that right.

Here's how you might do it:

public class DateUtils {
    private DateUtils() {}

    public static Date addDays(Date baseDate, int daysToAdd) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(baseDate);
        calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
        return calendar.getTime();
    }
}

Once you have this method tested and proven you can let the rest of you code just call it.

UPDATE: It's four years later, and JDK 8 has given us the new JODA-based time package. You should be using those classes, not the JDK 1.0 Calendar.

You need to change the lines that look like:

setup.add(day, -1);
setup.add(day, -10);

to

setup.add(GregorianCalendar.DAY_OF_MONTH, -1);
setup.add(GregorianCalendar.DAY_OF_MONTH, -10);

See GregorianCalendar for more information.

Gregorian calander has its own value you should be using to tell it what you are increasing where you are saying

setup.add(day, -1);

you should use the Gregorian calander value for day

setup.add(Calendar.DAY_OF_MONTH, -1);
Susie
Calendar c = new GregorianCalendar(2000, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);

More info on Calendar and its fields can be found here Calendar

Also try to look at this past post: here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!