GregorianCalendar常数日期
-
06-07-2019 - |
题
好的,我想让我的程序打印出日期:1/1/2009
但这就是打印出来的内容:
Thu Jan 01 00:00:00 EST 2009
从此代码中
GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
public void setStart()
{
startDate.setLenient(false);
Date date = new Date(startDate.getTimeInMillis());
System.out.println(date);
}
如何更改它以便仅打印出1/1/2009?
解决方案
使用 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());
}
您隐式调用 toString()
方法,该方法正确地打印出完整的内容。
顺便说一句,没有必要按照你的方式建立日期。在 Calendar
上调用 getDate()
会返回 Date
对象。
其他提示
目前, 正在调用Date.toString()
方法以显示 String 表示/docs/api/java/util/GregorianCalendar.html"rel =“nofollow noreferrer”> GregorianCalendar
实例。
需要做的是创建 DateFormat
将生成所需的 String
表示。 DateFormat
对象可用于使用 Date 实例格式化为所需的格式docs / api / java / text / DateFormat.html #format(java.util.Date)“rel =”nofollow noreferrer“> format
方法。
实现所需要的最简单方法是使用 SimpleDateFormat
类,其中包含构造函数,它采用格式字符串以所需的形式输出 Date
。
Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1);
DateFormat df = new SimpleDateFormat("M/d/yyyy");
System.out.println(df.format(calendar.getTime()));
输出
1/1/2009
不隶属于 StackOverflow