본문 바로가기
웹프로그래밍/Java

[JAVA] 날짜 유용한 메서드

by Seras 2017. 8. 28.
반응형

/**

    * getDiffDays 메서드

    * 시작일부터 종료일까지 사이의 날짜를 배열에 담아 리턴

    * ( 시작일과 종료일을 모두 포함한다 )

    * @param fromDate yyyyMMdd 형식의 시작일

    * @param toDate yyyyMMdd 형식의 종료일

    * @return yyyyMMdd 형식의 날짜가 담긴 배열

    */

  public static String[] getDiffDays(String fromDate, String toDate) {

     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

     Calendar cal = Calendar.getInstance();

     try {

         cal.setTime(sdf.parse(fromDate));

     } catch (Exception e) {}

     int count = getDiffDayCount(fromDate, toDate);

     // 시작일부터

     cal.add(Calendar.DATE, -1);

     // 데이터 저장

     List list = new ArrayList();

     for (int i = 0; i <= count; i++) {

         cal.add(Calendar.DATE, 1);

         list.add(sdf.format(cal.getTime()));

     }

     String[] result = new String[list.size()];

     list.toArray(result);

     return result;

}


   /**

    * getDiffDayCount 메서드

    * 두날짜 사이의 일수를 리턴

    * @param fromDate yyyyMMdd 형식의 시작일

    * @param toDate yyyyMMdd 형식의 종료일

    * @return 두날짜 사이의 일수

    */

public static int getDiffDayCount(String fromDate, String toDate) {

     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

     try {

         return (int)((sdf.parse(toDate).getTime() - sdf.parse(fromDate)

             .getTime()) / 1000 / 60 / 60 / 24);

     } catch (Exception e) {

         return 0;

     }

}



반응형

'웹프로그래밍 > Java' 카테고리의 다른 글

java null  (0) 2017.09.26
[Mybatis] insert type, jdbcType, javaType  (1) 2017.09.12
java.lang.NoSuchMethodError  (0) 2017.08.22
날짜 비교 compareTo  (0) 2017.08.22
[JAVA] eclipse hotswap (서버재구동없이)  (2) 2017.08.14