Search code examples
javagregorian-calendar

Gregorian Calendar "cal.add" Method Issues


I am currently attempting to write a program which returns the date 100 days from the current date of today. Here's the code:

public class gregorianCalendar {
    public static void main(String[] args){
        Calendar cal = new GregorianCalendar();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        int weekday = cal.get(Calendar.DAY_OF_WEEK);

        cal.add(Calendar.DAY_OF_MONTH, 100);
        System.out.print("100 days from today, the date will be: " + month);
        System.out.print("/" + dayOfMonth);
        System.out.println("/" + year);
    }
}

The output of the code gives the current date rather than the date 100 days after the current date. Any help would be greatly appreciated.


Solution

  • public class gregorianCalendar {
        public static void main(String[] args){
            Calendar cal = new GregorianCalendar();
            cal.add(Calendar.DAY_OF_MONTH, 100); // <------- add should be here
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
            int weekday = cal.get(Calendar.DAY_OF_WEEK);
    
            System.out.print("100 days from today, the date will be: " + month);
            System.out.print("/" + dayOfMonth);
            System.out.println("/" + year);
        }
    }
    

    OR

    public class gregorianCalendar {
        public static void main(String[] args){
            Calendar cal = new GregorianCalendar();
            // --------------- Current Date ------------
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
            int weekday = cal.get(Calendar.DAY_OF_WEEK);
            System.out.print("today, the date is: " + month);
            System.out.print("/" + dayOfMonth);
            System.out.println("/" + year);    
    
    
            // ---------- Current date + 100------------
            cal.add(Calendar.DAY_OF_MONTH, 100);
            System.out.print("100 days from today, the date will be: " + cal.get(Calendar.MONTH));
            System.out.print("/" + cal.get(Calendar.DAY_OF_WEEK));
            System.out.println("/" + cal.get(Calendar.YEAR));
        }
    }