gpt4 book ai didi

java - 在日期中添加天数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:14 25 4
gpt4 key购买 nike

我有一个程序需要在 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.
}

我在“newDay = startDate.add(5, 1);”中收到错误 found void but expected int,我该怎么办?

最佳答案

Calendar对象有一个 add允许添加或减去指定字段的值的方法。

例如,

Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);

指定字段的常量可以在Calendar的“字段摘要”中找到。类。

仅供将来引用,The Java API Specification包含许多有关如何使用属于 Java API 的类的有用信息。


更新:

I am getting the error found void but expected int, in 'newDay = startDate.add(5, 1);' What should I do?

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 不是日期的表示。它是日历的表示,以及它当前指向的位置。为了表示当前日历指向的位置,应该获得 Date。从 Calendar 使用 getTime方法。

关于java - 在日期中添加天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1416909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com