Adding Days to Calendar

后端 未结 4 1424
独厮守ぢ
独厮守ぢ 2021-01-05 07:08

I\'m new to this site and I have just started learning Java. I\'m trying to add couple days to the GregorianCalendar but it doesn\'t work. Here... (Ignore the top chunk), it

4条回答
  •  清歌不尽
    2021-01-05 07:28

    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.

提交回复
热议问题