본문 바로가기
💻Tech/☕Java

[Java] 날짜 더하기, 빼기 코드

by _viper_ 2019. 6. 12.
반응형

   /**
    * 날짜 더하기
    * 
    * @param dataeFormat yyyyMMdd ..
    * @param strDate 20190612 ..
    * @param dateUnit DATE or HOUR
    * @param addDate 1, -1 ...
    * @return
    */
   public static String dateAdd(String dataeFormat, String strDate, String dateUnit, int addDate) {
       DateFormat dateFormat = null;
       Date date = new Date();
       
       try {
           dateFormat = new SimpleDateFormat(dataeFormat);
           date = dateFormat.parse(strDate);
       } catch (ParseException e) {
    	   System.out.println(e.getMessage());
       }
       
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       if ("DATE".equals(dateUnit)) {
           cal.add(Calendar.DATE, addDate);
       } else if ("HOUR".endsWith(dateUnit)) {
           cal.add(Calendar.HOUR, addDate);
       } 
       return dateFormat.format(cal.getTime());
   }