문제

09 년 1 월 1 일부터 시작 해야하는 프로그램이 있으며 새로운 날을 시작하면 다음 날 프로그램이 표시됩니다. 이것이 내가 지금까지 가지고있는 것입니다.

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.
}

'newday = startDate.add (5, 1); 어떻게해야합니까?

도움이 되었습니까?

해결책

그만큼 Calendar 객체가 있습니다 add 지정된 필드의 값을 추가하거나 빼게하는 방법.

예를 들어,

Calendar c = new GregorianCalendar(2009, Calendar.JANUARY, 1);
c.add(Calendar.DAY_OF_MONTH, 1);

필드를 지정하기위한 상수는 Calendar 수업.

향후 참조를 위해 Java API 사양 Java API의 일부인 클래스를 사용하는 방법에 대한 유용한 정보가 많이 포함되어 있습니다.


업데이트:

'newday = startDate.add (5, 1); 어떻게해야합니까?

그만큼 add 방법은 아무것도 반환하지 않으므로 호출 결과를 할당하려고합니다. Calendar.add 유효하지 않습니다.

컴파일러 오류는 하나가 할당하려고한다는 것을 나타냅니다. void 유형의 변수로 int. "아무것도"에 할당 할 수 없으므로 이것은 유효하지 않습니다. int 변하기 쉬운.

단지 추측이지만 아마도 이것은 달성하려는 것일 수 있습니다.

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

고려해야 할 것은 무엇입니다 Calendar 사실입니다.

Calendar 날짜의 표현이 아닙니다. 그것은 달력의 표현이며 현재 가리키는 곳입니다. 현재 달력이 지적되는 위치를 표현하기 위해서는 Date ~로부터 Calendar 사용 getTime 방법.

다른 팁

현명하게 스윙 할 수 있다면, 모든 날짜/시간 요구 사항을 Joda로 옮기십시오. Joda는 훨씬 더 나은 라이브러리입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top