将日期添加到日期
我有一个程序需要在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. }
我在’newDay = startDate.add(5,1);’中得到错误,但是预期为int。 我该怎么办?
Calendar
对象有一个add
方法,允许用户添加或减去指定字段的值。
例如,
Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1); c.add(Calendar.DAY_OF_MONTH, 1);
可以在Calendar
类的“字段摘要”中找到用于指定字段的常量。
仅供将来参考, Java API规范包含许多有关如何使用作为Java API一部分的类的有用信息。
更新:
我在’newDay = startDate.add(5,1);’中得到错误,但是预期为int。 我该怎么办?
add
方法不返回任何内容,因此,尝试分配调用Calendar.add
的结果无效。
编译器错误表示正在尝试将void
分配给类型为int
的变量。 这是无效的,因为无法为int
变量赋予“nothing”。
只是猜测,但也许这可能是想要实现的目标:
// 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
实际上是什么。
Calendar
不是日期的表示。 它是日历的表示forms,也是当前指向的日历。 为了获得当前日历指向的位置,应使用getTime
方法从Calendar
获取Date
。
如果你可以明智地把它变成需求,把你所有的日期/时间需求转移到JODA,这是一个更好的库,额外的奖励几乎所有东西都是不可变的,这意味着multithreading是免费的。