java 返回传入日期的前或后第n个年\月\日的日期

  /**
     * 返回傳入日期的前或后第n个月的日期, 如果 lisdate 为now, 则代表当前日期
     *
     * eg: ("2020-12-11", 1) -> 2020-11-11; ("2020-12-11", 2) -> 2020-02-11
     */
    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);//在这里可通过改变MONTH属性选择计算年、月、日、周、时、分、秒,
        String time = format.format(c.getTime());

        return time;
    }

 

posted @ 2021-05-18 15:50  狴颜丶领衔  阅读(128)  评论(0编辑  收藏  举报