0

I want to get Start date and End date of a Month when a month select from a combo box. The combo box is filled with months like January, February..... when i select a month in combo box, i want to get the Start and End date of that month with current year. but here in the below code, year is specified in a text box. but i want to get the current year. not from text box. Please help me to solve this problem. thanks for advance.

this is the code i have tried

cal.set(Calendar.MONTH, cmbMonth.getSelectionModel().getSelectedIndex());
 int yearpart = Integer.parseInt(txtYear.getText());
 int monthPart = cmbMonth.getSelectionModel().getSelectedIndex();
 int dateDay = 1;
     cal.set(yearpart, monthPart, dateDay);
     int numOfDaysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
     System.out.println("Number of Days: " + numOfDaysInMonth);
     System.out.println("First Day of month: " + cal.getTime());
     cal.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
     System.out.println("Last Day of month: " + cal.getTime());

When I select month February in combo box . i want output like this

  First Day of month: 2019-02-1
  Last Day of month: 2019-02-28

Now i got this kind of output

First Day of month: Fri Feb 01 11:32:47 IST 2019
Last Day of month: Thur Feb 28 11:32:47 IST 2019

1 Answers1

1

You can use YearMonth:

int year = LocalDate.now().getYear();
String month = "January";
YearMonth yearMonth = YearMonth.of(year, Month.valueOf(month.toUpperCase()));

System.out.println(LocalDate.of(yearMonth.getYear(), yearMonth.getMonth(), 1));
System.out.println(yearMonth.atEndOfMonth());
Pochmurnik
  • 780
  • 6
  • 18
  • 35
  • 3
    Does this work on Java 7? It does if you use the backport of java.time. [ThreeTen Backport](https://www.threeten.org/threetenbp/). – Ole V.V. Oct 10 '19 at 11:16