在日期中添加天数
我有一个计划需要在 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.
}
我收到错误 found void but Expected int, in 'newDay = startDate.add(5, 1);' 我应该怎么办?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
日历
对象有一个add
方法,允许添加或减去指定字段的值。例如,
用于指定字段的常量可以在
日历
类。仅供将来参考,Java API 规范包含许多有关以下内容的有用信息:如何使用属于 Java API 的类。
更新:
add
方法不会返回任何内容,因此,尝试分配调用Calendar.add
的结果是无效的。编译器错误表明有人试图将
void
分配给类型为int
的变量。这是无效的,因为不能将“无”分配给int
变量。只是猜测,但这可能就是想要实现的目标:
输出:
需要考虑的是
Calendar
实际是什么。Calendar
不是日期的表示。它表示日历及其当前指向的位置。为了获得日历当前指向的位置的表示,应该获取 日历 中获取“html” rel="noreferrer">日期
/docs/api/java/util/Calendar.html#getTime()" rel="noreferrer">getTime
方法。The
Calendar
object has anadd
method which allows one to add or subtract values of a specified field.For example,
The constants for specifying the field can be found in the "Field Summary" of the
Calendar
class.Just for future reference, The Java API Specification contains a lot of helpful information about how to use the classes which are part of the Java API.
Update:
The
add
method does not return anything, therefore, trying to assign the result of callingCalendar.add
is not valid.The compiler error indicates that one is trying to assign a
void
to a variable with the type ofint
. This is not valid, as one cannot assign "nothing" to anint
variable.Just a guess, but perhaps this may be what is trying to be achieved:
Output:
What needs to be considered is what
Calendar
actually is.A
Calendar
is not a representation of a date. It is a representation of a calendar, and where it is currently pointing at. In order to get a representation of where the calendar is pointing at at the moment, one should obtain aDate
from theCalendar
using thegetTime
method.如果您可以明智地调整它的要求,请将所有日期/时间需求移至 JODA,这是一个更好的库,还有一个额外的好处,几乎所有内容都是不可变的,这意味着多线程是免费的。
If you can swing it requirement wise, move all your date/time needs to JODA, which is a much better library, with the added bonus that almost everything is immutable, meaning multithreading comes in for free.