Java 获取当前时间一周、一个月、一年以前的时间

  1. 使用Calendar的实现
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
Date now = new Date();
//一周以前
calendar.setTime(now);
calendar.add(Calendar.DATE, -7);
String formatDate = format.format(calendar.getTime());
System.out.println("一周以前:" + formatDate);

//一月以前
calendar.setTime(now);
calendar.add(Calendar.MONTH, -1);
formatDate = format.format(calendar.getTime());
System.out.println("一月以前:" + formatDate);


//一年以前
calendar.setTime(now);
calendar.add(Calendar.YEAR, -1);
formatDate = format.format(calendar.getTime());
System.out.println("一年以前:" + formatDate);

2.使用org.apache.commons.lang.time.DateUtils实现

System.out.println("一周以前:" + format.format(DateUtils.addWeeks(now,-1)));
System.out.println("一月以前:" + format.format(DateUtils.addMonths(now,-1)));
System.out.println("一年以前:" + format.format(DateUtils.addYears(now,-1)));

这里写图片描述

猜你喜欢

转载自blog.csdn.net/tmaczt/article/details/82698365