コード例 #1
0
 /**
  * 获取新的日期 + 月份
  *
  * @param date1 the date1
  * @param month the month
  * @return the date
  */
 public static Date addMonths(Date date1, int month) {
   return DateUtils.addMonths(date1, month);
 }
コード例 #2
0
  private String getFormatDate(String infmt, String date, String outfmt) throws ParseException {
    if (date == null || date.length() <= 0) {
      return "";
    }
    if (date.length() == 1) {
      Date today = Calendar.getInstance().getTime();
      return DateFormatUtils.format(today, outfmt);
    } else {
      int plus = date.indexOf('+');
      int minus = date.indexOf('-');
      if (plus > 0 || minus > 0) {
        Date today = Calendar.getInstance().getTime();
        String type = date.substring(0, 1);
        String sign = date.substring(1, 2);
        int amount = 0;
        try {
          amount = Integer.parseInt(date.substring(2));
        } catch (NumberFormatException e) {
          LOG.error("Exception", e);
          return null;
        }
        if (("+").equals(sign)) {
          if (("D").equals(type)) {
            return DateFormatUtils.format(DateUtils.addDays(today, amount), outfmt);
          } else if (("M").equals(type)) {
            return DateFormatUtils.format(DateUtils.addMonths(today, amount), outfmt);
          } else if (("Y").equals(type)) {
            return DateFormatUtils.format(DateUtils.addYears(today, amount), outfmt);
          }
        } else if (("-").equals(sign)) {
          if (("D").equals(type)) {
            return DateFormatUtils.format(DateUtils.addDays(today, -amount), outfmt);
          } else if (("M").equals(type)) {
            return DateFormatUtils.format(DateUtils.addMonths(today, -amount), outfmt);
          } else if (("Y").equals(type)) {
            return DateFormatUtils.format(DateUtils.addYears(today, -amount), outfmt);
          }
        } else {
          return null;
        }
      }
    }

    // date 형식이  infmt 에 맞지 않다면 date 를 infmt 에 맞추어줌.
    StringBuilder sDate = new StringBuilder(date);
    int len = date.length();

    if (("yyyyMMddHHmm").equals(infmt) && len < 12) {
      for (int i = len; i < 12; i++) {
        sDate.append("0");
      }
    } else if (("yyyyMMddHHmmss").equals(infmt) && len < 14) {
      for (int i = len; i < 14; i++) {
        sDate.append("0");
      }
    }

    SimpleDateFormat sdf = new SimpleDateFormat(infmt);
    Date d = sdf.parse(sDate.toString());
    sdf.applyPattern(outfmt);

    return sdf.format(d);
  }