2017-10-13 5 views
-9

주어진 연도 또는 현재 연도의 모든 달을 반복하고 각 달의 첫 번째 날짜와 마지막 날짜를 가져오고 싶습니다. 예를 들면. 현재 연도는 2017 년과 10 월입니다. 그래서 저는 2017 년 10 월부터 2017 년에 Decemeber로 돌아가서 10 월 첫 데이트가 2017-10-01이고 마지막 데이트가 2017-10-31이 될 때마다 매월 첫날과 마지막 날을 가져오고 싶습니다. 달력을 사용하여현재 연도의 각 월을 반복하고 매월의 첫 번째 날짜와 마지막 날을 얻는 방법

+0

프로그래밍 노력 –

+2

힌트를 귀하의 질문에 설명 : 당신이 할 수있는 경우 java.util.Calendar'를 사용하는 것보다 훨씬 좋을 것입니다. –

+1

[주어진 문자열 날짜에 해당 월의 마지막 날 가져 오기] 가능한 복제본 (https://stackoverflow.com/questions/13624442/getting-last-day-of-the-month-in-given-string-date) –

답변

1

(모든 자바 버전에서 작동) :

 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); 
     } 

새로운 자바 8 날짜/시간 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); 
     } 
+0

고맙습니다. –

+1

좋은 답변입니다. 'for' 루프를'EnumSet'과'TemporalAdjuster'가 아닌'YearMonth'를 사용하여'Month' 열거 형을 사용하도록 바꾸면 약간 재미있게 될 수 있습니다 : for (Month month : EnumSet.range (today.getMonth (today.getMonth), Month.DECEMBER))'예제보기 [IdeOne.com에서의 코드 실행] (https://www.ideone.com/G4BwY6) –

+0

내 게시물을 편집 할 수 있습니다. :) – Tuco