Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last day of Month

For getting last date of month I have written this function

/**
 * @param month integer value of month
 * @param year integer value of month
 * @return last day of month in MM/dd/YYYY format
 */
private static String getDate(int month, int year) {
    Calendar calendar = Calendar.getInstance();
    // passing month-1 because 0-->jan, 1-->feb... 11-->dec
    calendar.set(year, month - 1, 1);
    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
    Date date = calendar.getTime();
    DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/YYYY");
    return DATE_FORMAT.format(date);
}

for all the inputs its working fine with one exception when the month is December, i.e. getDate(12, 2012) returns 12/31/2013 but it should return 12/31/2012. Please explain the behavior and solution too.

like image 233
Anurag Tripathi Avatar asked Oct 21 '13 07:10

Anurag Tripathi


People also ask

How do I get the last day of the month in Excel?

=EOMONTH(A2, -1) - returns the last day of the month, one month before the date in cell A2.

How do I get the last day of the month in C#?

AddMonths(1). AddDays(-3);". (-3) is the day amount so 0 of next month is basicly the last day of current month.

How do I get the last day of the month in Google Sheets?

Use =eomonth((eomonth(today(),0)),-2)+1 for use when you want previous from today. For the last day of the previous month, use =eomonth((eomonth(today(),0)),-1) .


4 Answers

Change YYYY to yyyy

DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");   

YYYY is wrong dateformat

like image 73
rohan kamat Avatar answered Sep 29 '22 03:09

rohan kamat


Try this

calendar.add(Calendar.MONTH, month);   calendar.set(Calendar.DAY_OF_MONTH, 1);   calendar.add(Calendar.DATE, -1);    Date date = calendar.getTime(); 
like image 21
Scary Wombat Avatar answered Sep 29 '22 01:09

Scary Wombat


Try to use Joda-Time, it's more simple :

private static String getLastDayOfMonth(int month, int year) {
    LocalDate lastDayOfMonth = new LocalDate(year, month, 1).dayOfMonth().withMaximumValue();
    return lastDayOfMonth.toString("MM/dd/yyyy");
}
like image 25
Oussama Zoghlami Avatar answered Sep 29 '22 03:09

Oussama Zoghlami


private static String getDate(int month, int year) {
    Calendar calendar = Calendar.getInstance();

    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));

    Date date = calendar.getTime();
    DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
    return DATE_FORMAT.format(date);
}
like image 36
Elton Wang Avatar answered Sep 29 '22 03:09

Elton Wang