(JAVA日期时间)在原有日期时间上加几个月或几天
在原有的时间上添加几个月:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 Date date = new Date(); System.out.println(df.format(date)); // 当前系统时间 Date newDate = stepMonth(date, 1); System.out.println("当前时间前1个月的日期:" + df.format(newDate)); public static Date stepMonth(Date sourceDate, int month) { Calendar c = Calendar.getInstance(); c.setTime(sourceDate); c.add(Calendar.MONTH, month); return c.getTime(); }
在原有的时间上添加几天:
public static void main(String[] args) throws ParseException { String time = "2019-6-02 11:05:51";//当前时间 int num = 15;//加的天数 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date currdate = format.parse(time); System.out.println("初始的时间是:" + time); Calendar ca = Calendar.getInstance(); ca.setTime(currdate); ca.add(Calendar.DATE, num); currdate = ca.getTime(); String enddate = format.format(currdate); System.out.println("增加天数以后的时间:" + enddate); }