Question

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?

Was it helpful?

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.

OTHER TIPS

Currently, the Date.toString() method is being called to display the String representation of the GregorianCalendar instance.

What needs to be done is to create a DateFormat which will produce a String representation which is desired. The DateFormat object can be used to format a Date instance to the desired formatting using the format method.

The simplest way to achieve what is desired is to use the SimpleDateFormat class, which has a constructor which takes a format string to output the Date in a desired form.

Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1);
DateFormat df = new SimpleDateFormat("M/d/yyyy");
System.out.println(df.format(calendar.getTime()));

Output

1/1/2009
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top