天天看點

Java擷取指定日期或目前日期的上個月份或其他月份的日期 - Java

/**
   * 傳回傳入日期的前或後第n個月的日期, 如果 lisdate 為now, 則代表目前日期
   * 
   * eg: ("2020-12-11", 1) -> 2020-11-11; ("2020-12-11", 2) -> 2020-02-11
   * 
   * @param yearmonth
   * @return
   * @AddBy 2020-12-24
   * @author xyLi
   */
  public static String getDateByMonth(String lisdate, int interval) {
    DateFormat format2 =  new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    if (!"now".equals(lisdate)) {
      try {
        date = format2.parse(lisdate);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
    c.add(Calendar.MONTH, interval);
    String time = format.format(c.getTime());

    return time;
  }
  
  /**
   * 傳回傳入年月的前或後第n個月的年月, 如果 lisdateYearmonth 為now,則代表目前年月
   * 
     * eg: ("202012", -1) -> 202011 ; ("202012", 2) -> 202102
   * @param yearmonth
   * @return
   * @AddBy 2020-12-24
     * @author xyLi 
     * 
   */
  public static String getYearMonthByMonth(String lisdateYearmonth, int interval) {
    DateFormat format2 =  new SimpleDateFormat("yyyyMM");
    Date date = new Date();
    if (!"now".equals(lisdateYearmonth)) {
      try{
          date = format2.parse(lisdateYearmonth);
      }catch(Exception e){
          e.printStackTrace();
      }
    }
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    SimpleDateFormat format =  new SimpleDateFormat("yyyyMM");
    c.add(Calendar.MONTH, interval);
    String time = format.format(c.getTime());

    return time;
  }