【问题标题】:Increment calendar with day以天为单位增加日历
【发布时间】:2013-11-12 17:02:32
【问题描述】:

当我在日历中增加天数时,我遇到了一个奇怪的问题。我想循环一年中的每一天。这是我的代码

Date d = null;
SimpleDateFormat textFormat = new SimpleDateFormat("dd-MM-yyyy");
String paramDateAsString = "10-1-2012";
d = textFormat.parse(paramDateAsString);
Calendar cal = Calendar.getInstance(); 
cal.setTime(d);

for(int i = 0; i < 365; i++) {
   cal.add(Calendar.DAY_OF_YEAR, 1);
   System.out.println(cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+1+"-         "+cal.get(Calendar.DAY_OF_MONTH)+" 00:00:00'");
}

我得到这个输出:

...
2012-01-29 00:00:00'
2012-01-30 00:00:00'
2012-01-31 00:00:00'
2012-11-1 00:00:00'
2012-11-2 00:00:00'
...

【问题讨论】:

    标签: java date time calendar


    【解决方案1】:

    这就是问题所在:

    "-"+cal.get(Calendar.MONTH)+1
    

    这实际上是在执行 string 连接 - 它是有效的

    ("-" + cal.get(Calendar.MONTH)) + 1
    

    所以当cal.get(Calendar.MONTH) 返回 1 时,这实际上是:

    ("-" + 1) + 1 // which is...
    "-1" + 1 // which is...
    "-11"
    

    可以只用括号括起来:

    "-" + (cal.get(Calendar.MONTH) + 1)
    

    ...但最好使用SimpleDateFormat 执行格式化而不是手动执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      相关资源
      最近更新 更多