-2

I wanna loop through all the months of a given year or current year and get first and last date of each month. For example. Current year is 2017 and month October. So i wanna loop from October, 2017 to Decemeber, 2017 and fetch first and last date of each month like october first date is 2017-10-01 and last date will be 2017-10-31.

Ashutosh Srivastava
  • 103
  • 1
  • 1
  • 10

1 Answers1

10

By using Calendar (works in all Java versions) :

        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        cal.clear();
        cal.set(Calendar.YEAR, year);

        for (int currentMonth = month; currentMonth < 12; currentMonth++) {

            cal.set(Calendar.MONTH, currentMonth);

            //first day :
            cal.set(Calendar.DAY_OF_MONTH, 1);
            Date firstDay = cal.getTime();
            System.out.println("firstDay=" + firstDay);

            //last day
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date lastDay = cal.getTime();
            System.out.println("lastDay=" + lastDay);
        }

By using new Java 8 date/time API :

LocalDate date = LocalDate.now();
        int month = date.getMonthValue();

        for (int currentMonth = month; currentMonth <= 12; currentMonth++) {
            date = date.withMonth(currentMonth);

            //start of month :
            LocalDate firstDay = date.withDayOfMonth(1);
            System.out.println("firstDay=" + firstDay);

            //end of month
            LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
            System.out.println("lastDay=" + lastDay);
        }

EDIT JAVA8+

Another aproach to this could be:Documentation

import static java.time.temporal.TemporalAdjusters.*;//to get functions firstDayOfMonth() and lastDayOfMonth()
...
LocalDate initialdate= ...
LocalDate localDateNow = ...
DateTimeFormatter format1 = ...

for(LocalDate date = initialdate; date.isBefore(localDateNow); date = date.plusMonths(1)) { //Could be plusdays if you want to interate day by day

    LocalDate dtini = date.with(firstDayOfMonth());
    LocalDate dtend = dtini.with(lastDayOfMonth());
    //LocalDate dtend = dtini.plusDays(14); //If you want from day 1 do 15

    //TODO: Use dtini and dtend to your like
    System.out.println("dtini =" + format1.format(dtini));
    System.out.println("dtend =" + format1.format(dtend));

}
Henrique C.
  • 948
  • 1
  • 14
  • 36
Tuco
  • 493
  • 2
  • 6
  • 18
  • 3
    Good Answer. You could get a little fancier by replacing that `for` loop to use the `Month` enum with an `EnumSet`, and `YearMonth` rather than `TemporalAdjuster`: `for ( Month month : EnumSet.range( today.getMonth( ) , Month.DECEMBER ) )` See example [code run live at IdeOne.com](https://www.ideone.com/G4BwY6) – Basil Bourque Oct 14 '17 at 01:21
  • you're welcome to edit my post :) – Tuco Oct 14 '17 at 05:52