2012-03-14 22 views
96

Necesito obtener la primera fecha (como org.joda.time.LocalDate) de un mes y la última. Obtener el primero es trivial, pero obtener el último parece necesitar algo de lógica ya que los meses tienen diferente duración y la duración de febrero incluso varía con los años. ¿Existe un mecanismo para esto ya incorporado a JodaTime o debería implementarlo yo mismo?¿Cómo obtener la última fecha de un mes en particular con JodaTime?

+1

Solo un aviso, esto también funciona con los tipos 'DateTime' :) – vikingsteve

Respuesta

186

¿Qué tal:

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

dayOfMonth() devuelve un LocalDate.Property que representa el "día del mes" campo de una manera que conoce el LocalDate de origen.

Si llega el caso, el método es aun withMaximumValue()documented a recomendaría para esta tarea en particular:

Esta operación es útil para obtener una LocalDate en el último día del mes, como extensiones de los meses varían.

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

@Jon Skeet ¿Cómo obtener esto usando la nueva API Date and Time de Java 8? –

+4

@ WarrenM.Nocos: Utilizaría 'dt.with (TemporalAdjusters.lastDayOfMonth())' –

0

Una cuestión de edad, sino un resultado superior Google cuando yo estaba buscando para ello.

Si alguien necesita el último día real como un int en lugar de utilizar JodaTime usted puede hacer esto:

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

Usando JodaTime, podemos hacer esto:

 

    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); 
    }

Como se describe aquí, en mi pequeña esencia en github: A JodaTime and java.util.Date Util Class with a lot of usefull functions.

5

Otro método simple es este:

//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

¿Qué ocurre entonces si su mes es = 12? – jon

Cuestiones relacionadas