2012-03-14 4 views
96

나는 한 달과 마지막 달의 첫 데이트 (org.joda.time.LocalDate)를 얻어야합니다. 첫 번째 방법은 사소한 일이지만, 마지막 달은 길이가 다르며 2 월 길이가 몇 년에 걸쳐 변하기 때문에 논리가 필요합니다. JodaTime에 이미 내장 된 메커니즘이 있습니까? 아니면 직접 구현해야합니까?JodaTime으로 특정 달의 마지막 날짜를 얻는 방법은 무엇입니까?

+1

그냥 헤드 업, 이것도'DateTime' 유형과 함께 작동합니다 :) – vikingsteve

답변

186

방법에 대해 :

LocalDate endOfMonth = date.dayOfMonth().withMaximumValue(); 

dayOfMonth()가 발생 LocalDate 알고있는 방법으로 필드 "달의 일"을 나타내는 LocalDate.Property를 반환합니다. 공교롭게도

withMaximumValue() 방법이 특정 작업을 위해 그것을 추천도 documented입니다 :

이 작업은 달의 길이가 달라질 수로, 달의 마지막 날에 LOCALDATE를 얻기위한 유용합니다.

LocalDate lastDayOfMonth = dt.dayOfMonth().withMaximumValue(); 
+0

@ 존 스키켓 어떻게 Java 8의 새로운 날짜와 시간 API를 사용하여 이것을 얻으시겠습니까? –

+4

@ WarrenM.Nocos :'dt.with (TemporalAdjusters.lastDayOfMonth()) '를 사용합니다 –

0

나는이 찾고 있던 오래된 질문하지만, 최고 구글 결과. 누군가가 대신이 할 수있는 JodaTime 사용하여 int로 실제 마지막 날을 필요로하는 경우

: JodaTime를 사용

public static final int JANUARY = 1; 

public static final int DECEMBER = 12; 

public static final int FIRST_OF_THE_MONTH = 1; 

public final int getLastDayOfMonth(final int month, final int year) { 
    int lastDay = 0; 

    if ((month >= JANUARY) && (month <= DECEMBER)) { 
     LocalDate aDate = new LocalDate(year, month, FIRST_OF_THE_MONTH); 

     lastDay = aDate.dayOfMonth().getMaximumValue(); 
    } 

    return lastDay; 
} 
-1

을, 우리는이 작업을 수행 할 수 있습니다

 

    public static final Integer CURRENT_YEAR = DateTime.now().getYear(); 

    public static final Integer CURRENT_MONTH = DateTime.now().getMonthOfYear(); 

    public static final Integer LAST_DAY_OF_CURRENT_MONTH = DateTime.now() 
      .dayOfMonth().getMaximumValue(); 

    public static final Integer LAST_HOUR_OF_CURRENT_DAY = DateTime.now() 
      .hourOfDay().getMaximumValue(); 

    public static final Integer LAST_MINUTE_OF_CURRENT_HOUR = DateTime.now().minuteOfHour().getMaximumValue(); 

    public static final Integer LAST_SECOND_OF_CURRENT_MINUTE = DateTime.now().secondOfMinute().getMaximumValue(); 


    public static DateTime getLastDateOfMonth() { 
     return new DateTime(CURRENT_YEAR, CURRENT_MONTH, 
       LAST_DAY_OF_CURRENT_MONTH, LAST_HOUR_OF_CURRENT_DAY, 
       LAST_MINUTE_OF_CURRENT_HOUR, LAST_SECOND_OF_CURRENT_MINUTE); 
    }

이로 내 작은 여기에 설명 github에 관한 요지 : A JodaTime and java.util.Date Util Class with a lot of usefull functions.

5

또 다른 간단한 방법은 다음과 같습니다.

//Set the Date in First of the next Month: 
answer = new DateTime(year,month+1,1,0,0,0); 
//Now take away one day and now you have the last day in the month correctly 
answer = answer.minusDays(1); 
+0

월이 12 일 경우 어떻게됩니까? – jon

관련 문제