Kar*_*ren 9 java date gregorian-calendar
我有一个程序需要在1/1/09开始,当我开始新的一天,我的程序将在第二天显示.这是我到目前为止:
GregorianCalendar startDate = new GregorianCalendar(2009, Calendar.JANUARY, 1);
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
public void setStart()
{
startDate.setLenient(false);
System.out.println(sdf.format(startDate.getTime()));
}
public void today()
{
newDay = startDate.add(5, 1);
System.out.println(newDay);
//I want to add a day to the start day and when I start another new day, I want to add another day to that.
}
Run Code Online (Sandbox Code Playgroud)
我在'newDay = startDate.add(5,1);'中得到错误,但是预期为int 我该怎么办?
coo*_*ird 18
该Calendar对象具有add允许添加或减去指定字段的值的方法.
例如,
Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);
Run Code Online (Sandbox Code Playgroud)
用于指定字段的常量可以在类的"字段摘要"中找到Calendar.
仅供将来参考,Java API规范包含许多有关如何使用作为Java API一部分的类的有用信息.
更新:
我在'newDay = startDate.add(5,1);'中得到错误,但是预期为int 我该怎么办?
该add方法不返回任何内容,因此,尝试分配调用结果Calendar.add无效.
编译器错误表示正在尝试将a分配给void类型为的变量int.这是无效的,因为无法为int变量分配"无" .
只是一个猜测,但也许这可能是试图实现的:
// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2009, Calendar.JANUARY, 1);
// Get the current date representation of the calendar.
Date startDate = calendar.getTime();
// Increment the calendar's date by 1 day.
calendar.add(Calendar.DAY_OF_MONTH, 1);
// Get the current date representation of the calendar.
Date endDate = calendar.getTime();
System.out.println(startDate);
System.out.println(endDate);
Run Code Online (Sandbox Code Playgroud)
输出:
Thu Jan 01 00:00:00 PST 2009
Fri Jan 02 00:00:00 PST 2009
Run Code Online (Sandbox Code Playgroud)
需要考虑的是Calendar实际情况.
A Calendar不是日期的表示.它是日历的表示,以及它当前指向的位置.为了获得当前日历指向的位置的表示,应该Date从Calendar使用该getTime方法获得a .
| 归档时间: |
|
| 查看次数: |
45689 次 |
| 最近记录: |