我有一个程序需要在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的类的有用信息。


<强>更新

  

我发现错误发现无效但是   期望的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 实际上是什么。

Calendar 不是日期的表示。它是日历的表示,以及它当前指向的位置。为了获得日历指向的位置,应该获得 Calendar 获取html”rel =“noreferrer”> Date /docs/api/java/util/Calendar.html#getTime()“rel =”noreferrer“> getTime 方法。

其他提示

如果您可以明智地将其转移,请将所有日期/时间需求移至JODA,这是一个更好的库,并且额外的奖励几乎所有内容都是不可变的,这意味着多线程是免费的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top