last date of previous month returning 30 days for May

Mdhar9e :

I am using the below code to retrieve the last day in the previous month - Ex: May. But it is returning 30 days instead of 31.

The code given below

package net.vcmg.date;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

public class LastDayPreviousMonth {
    public static void main(String[] args) {
        Date lastDateOfPreviousMonth = addMonths(lastDayOfTheMonth(today()), -1);
        System.out.println("lastDateOfPreviousMonth: "+lastDateOfPreviousMonth);

    }

    //the below method is from Utils.java
    public static Date lastDayOfTheMonth(Date d) {
           Calendar cal = Calendar.getInstance();
           cal.setTime(d);
           int actualMax = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
           cal.set(Calendar.DAY_OF_MONTH, actualMax);
           return cal.getTime();
    }

    public static Date addMonths(Date date, int numMonths)
    {
        return DateUtils.addMonths(date, numMonths);
    }

    public static Date today()
    {
        return truncDate(now());
    }

    public static Date now()
    {
        // will cut-off milliseconds
        return new Date( (System.currentTimeMillis()/1000) * 1000);
    }

    public static Date truncDate (Date date) {
        return DateUtils.truncate(date, Calendar.DATE);
    }

}

Here, when i call the lastDateOfPreviousMonth in the main method, it is returning 30 days alone. Not the 31 , May contains 31 days actually. Please help.

Vitaly :

Try this:

public static void main(String[] args) {
        Date lastDateOfPreviousMonth = lastDayOfTheMonth(addMonths(today(), -1));
        System.out.println("lastDateOfPreviousMonth: " + lastDateOfPreviousMonth);

    }

When you call lastDayOfTheMonth for today() day will be 30. And after minus one month result expected will be 30, not 31.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127428&siteId=1