Search code examples
javagregorian-calendar

GregorianCalendar constant date


Ok, I want to make my program print out the date: 1/1/2009

But this is what it prints out:

Thu Jan 01 00:00:00 EST 2009

From this code

GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
public void setStart()
{
    startDate.setLenient(false);
    Date date = new Date(startDate.getTimeInMillis());
    System.out.println(date);
}

How can I change it so that it only prints out 1/1/2009?


Solution

  • Use SimpleDateFormat:

    GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
    public void setStart() {
      startDate.setLenient(false); 
      DateFormat df = new SimpleDateFormat("d/M/yyyy");
      df.format(startDate.getDate());
    }
    

    You're implicitly calling the toString() method which is (correctly) printing out the complete contents.

    By the way, there is no need to construct a date the way you're doing. Calling getDate() on a Calendar returns a Date object.