当我增加日历中的天数时,我遇到了一个奇怪的问题。我想循环过一年中的每一天。这是我的代码
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'
...
最佳答案
这就是问题:
"-"+cal.get(Calendar.MONTH)+1
这实际上是在执行字符串连接 - 它很有效
("-" + 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
来执行格式化,而不是手动执行。
关于java - 日历随日期递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19924837/