加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 添加日期到日期

发布时间:2020-12-14 16:21:06 所属栏目:Java 来源:网络整理
导读:我有一个程序,需要从1/1/09开始,当我开始新的一天,我的程序将显示第二天. 这是我到目前为止 GregorianCalendar startDate = new GregorianCalendar(2009,Calendar.JANUARY,1);SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy"); public void setStar
我有一个程序,需要从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.
}

我发现错误void but expected int,in’newDay = startDate.add(5,1);’
我该怎么办?

解决方法

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

例如,

Calendar c = new GregorianCalendar(2009,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的结果无效.

编译器错误表示一个人试图为int类型的变量分配一个void.这是无效的,因为不能将“nothing”赋给int变量.

只是一个猜测,但也许这可能是想要实现的:

// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2009,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

需要考虑的是日历实际上是什么.

日历不是日期的表示.它是一个日历的表示,它正在指向哪里.为了获取当前日历指向的位置,应使用getTime方法从日历中获取Date.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读