Notes - java - get the last day of a certain month of a certain year

public class LastDayOfMonth
{
    /**
     * Get the last day of a month
     *
     */
    public static String getLastDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //set year
        cal.set(Calendar.YEAR,year);
        //set month
        cal.set(Calendar.MONTH, month-1);
        //Get the maximum number of days in a month
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //Set the maximum number of days in the month in the calendar
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        // format the date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
         
        return lastDayOfMonth;
    }
 
    /**
     *    main
     */
    public static void main(String[] args)
    {
        String lastDay = getLastDayOfMonth(2014,5);
        System.out.println("Get the last day of the current month: " + lastDay);
    }
 
}    

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324549313&siteId=291194637
Recommended