Search code examples
javadate-formatgregorian-calendar

GregorianCalendar and DateFormat Java


I am trying to do a simple exercise where I take a date, add 90 days to it, and format it to something like this:

Monday, April 20, 1998.

I am to do this using GregorianCalendar and DateFormat. So far, I have this compiling code, but I get a runtime error where I cannot format the given Object as Date:

import java.util.*;
import java.text.*;

class Assignment21 {
    public static void main(String args[]) {
        GregorianCalendar ddate = new GregorianCalendar(1994, 10, 20);
        ddate.add(Calendar.DAY_OF_MONTH, 90);
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM dd, yyyy");
        String date = sdf.format(ddate);
    }
}

How can I correctly output the predefined GregorianCalendar date using DateFormat?


Solution

  • You have to correct your code:

    instead of

    String date = sdf.format(ddate);
    

    try:

    String date = sdf.format(ddate.getTime());