将日期添加到日期
我有一个程序需要在2009年1月1日开始,当我开始新的一天时,我的程序将在第二天显示。 这是我到目前为止有:将日期添加到日期
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.
}
我收到错误发现无效,但预计INT,在“newDay = startDate.add(5,1);” 我该怎么办?
Calendar
对象有一个add
方法,它允许添加或减去指定字段的值。
例如,
Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);
用于指定字段中的常数可以在Calendar
类的“字段摘要”中找到。
仅供将来参考,The Java API Specification包含大量关于如何使用属于Java API一部分的类的有用信息。
更新:
我正在错误发现空隙但 预期INT,在 'newDay = startDate.add(5,1);'我应该怎么做 ?
的add
方法不返回任何东西,因此,尝试指派调用Calendar.add
是无效的结果。
编译器错误表明正在尝试将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);
输出:
Thu Jan 01 00:00:00 PST 2009
Fri Jan 02 00:00:00 PST 2009
有什么需要考虑的是什么Calendar
实际上是。
A Calendar
不代表日期。它是日历的表示,以及它当前指向的位置。为了得到此时日历所指的位置,应使用getTime
方法从Calendar
获得Date
。
我正打算输入API的链接! – vpram86 2009-09-13 05:18:57
如果你可以摆动它的需求明智的,移动所有的日期/时间需要JODA,这是一个更好的图书馆,与几乎所有东西都是不变的额外奖金,这意味着多线程免费进来。
几个小时内约三个问题。也许是时候先看看API了。 – camickr 2009-09-13 05:22:34