1

我做了一个小程序来计算天数。从 5 月 22 日算起 150 天。但结果是 10 月 18 日。实际日期是 10 月 19 日。谁能帮我找出我的代码有什么问题。


Calendar mine = new GregorianCalendar(2013, Calendar.MAY,22);
    int month = Calendar.MAY;
    int counter = 0;
    for(int i=mine.get(Calendar.DAY_OF_MONTH);i<=mine.getActualMaximum(Calendar.DAY_OF_MONTH);i++){
    System.out.println("i "+i);

        counter++;
        System.out.println("counter "+counter);
    if(i==mine.getActualMaximum(Calendar.DAY_OF_MONTH)){
        month++;
        i=1;

        mine.set(2013, month, i);
        counter++;
        System.out.println("i "+i+" "+mine.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH));
        if(counter == 150){

        System.out.println("day "+i+ counter +"days"+ "month:"+ mine.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH));
        break;
        }
    }
        if(counter == 150){

        System.out.println("i "+i+" counter "+ counter +" date:"+mine.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH));
        break;
        }
        }
4

3 回答 3

3

您可以只add使用Calendar

Calendar mine = new GregorianCalendar(2013, Calendar.MAY,22);
mine.add(Calendar.DAY_OF_YEAR, 150);
System.out.println(mine.getTime());

将打印

Sat Oct 19 00:00:00 IST 2013

但是您的代码的真正问题是,您counter先递增,然后与150.

这样做,它应该修复你的代码

if(counter == 150){
   System.out.println("i "+i+" counter "+ counter +date:"+mine.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH));
   break;
}
counter++;
于 2013-05-24T06:29:44.347 回答
2

或者你可以使用 Joda DateTime:

import org.joda.time.DateTime;
....
System.out.println(new DateTime("2013-05-22").plusDays(150));
于 2013-05-24T06:34:33.917 回答
2
于 2017-03-02T05:34:54.127 回答