GregorianCalendar constant date

半世苍凉 提交于 2019-12-11 16:29:52

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/1416682/gregoriancalendar-constant-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!