2016-01-04 60 views
2

我正在尝试使用c.add(Calendar.DATE,1)更改按钮单击的日期。它应该增加一天。问题是,当月份发生变化时,日期会增加到32,而不是预期的1(1月份)。月份更改为2月份,但日期更改为32等等。 32-Feb-2016日历的添加方法会给出错误的值?

final TextView tv_date = (TextView) dialyReportView.findViewById(R.id.datepicker); 
@Override 
      public void onClick(View v) { 
       Calendar c; 
       c= Calendar.getInstance(); 
       c.add(Calendar.DATE,1); 
       SimpleDateFormat df= new SimpleDateFormat("DD-MMM-yyyy"); 
       String nextDate = df.format(c.getTime()); 
       tv_date.setText(nextDate); 
      } 
     }); 

我是新手编程,所以任何帮助表示赞赏。谢谢! :)

+0

谢谢@AndyTurner你能帮助解决方案:) – AndroidNewBee

+1

请阅读关于编写[最小,完整,可验证示例](http://www.stackoverflow.com/help/mcve)。事实上,这是与Android代码相关的,或者您是否可以在简单的Java程序中重现相同的问题,只需阅读此问题即可运行该程序? –

+0

您的编辑不会保留完整的代码。例如,什么是'c',并且这个代码不能单独运行。 –

回答

4

问题是,您正在使用D(年中的某天)而不是d(月中的某天)。例如,下面的代码输出31-Jan-201532-Feb-2015

Calendar c = Calendar.getInstance(); 
c.set(2015, 0, 31); 
c.SimpleDateFormat df= new SimpleDateFormat("DD-MMM-yyyy"); 
System.out.println(df.format(c.getTime())); 
c.add(Calendar.DATE,1); 
System.out.println(df.format(c.getTime())); 

,而下面的输出31-Jan-201501-Feb-2015

Calendar c = Calendar.getInstance(); 
c.set(2015, 0, 31); 
c.SimpleDateFormat df= new SimpleDateFormat("dd-MMM-yyyy"); 
System.out.println(df.format(c.getTime())); 
c.add(Calendar.DATE,1); 
System.out.println(df.format(c.getTime())); 
3

更改您的日期格式代码行如下。

SimpleDateFormat df = new SimpleDateFormat(“dd-MMM-yyyy”);