java get the first date and last date of given month and given year

calendar, date, java

Solution

To get the Start Date

    GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);
    java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
    System.out.println(monthEndDate);

(Note : in the Start date the day =1)

for the formatted

SimpleDateFormat format = new SimpleDateFormat(/////////add your format here);
System.out.println("Calculated month end date : " + format.format(calculatedDate));

Problem

I am trying to get the first date and the last date of the given month and year. I used the following code to get the last date in the format yyyyMMdd. But couldnot get this format. Also then I want the start date in the same format. I am still working on this. Can anyone help me in fixing the below code. ``` public static java.util.Date calculateMonthEndDate(int month, int year) { int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int day = daysInAMonth[month]; boolean isLeapYear = new GregorianCalendar().isLeapYear(year); if (isLeapYear && month == 2) { day++; } GregorianCalendar gc = new GregorianCalendar(year, month - 1, day); java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime()); return monthEndDate; } public static void main(String[] args) { int month = 3; int year = 2076; final java.util.Date calculatedDate = calculateMonthEndDate(month, year); SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); format.format(calculatedDate); System.out.println("Calculated month end date : " + calculatedDate); } ```

Original source

Related problems