0
点赞
收藏
分享

微信扫一扫

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;
}


举报

相关推荐

0 条评论