/** * 获取前一个月的日期 * * @return 前一个月的日期 */ public static String getTodayBeforeMonth() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date currentTime = new Date();// 获得当前系统时间 long now = currentTime.getTime();// 返回自 1970 年 1 月 1 日 00:00:00 GMT // 以来此Date 对象表示毫秒数 currentTime = new Date(now - 86400000 * 24); long now1 = currentTime.getTime(); currentTime = new Date(now1 - 86400000 * 6); String current = formatter.format(currentTime); return current; } public static void main(String[] args) { System.out.println(DateUtil.getTodayBeforeMonth()); }
// 刚才那种方式因为担忧int溢出问题,因此采用了两次相乘,还能够用以下方法 结果是同样的 获取 /** * 前一个月的日期 * @return 前一个月的日期 */ public static String getTodayBeforeMonth() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date currentTime = new Date();// 获得当前系统时间 long now = currentTime.getTime();// 返回自 1970 年 1 月 1 日 00:00:00 GMT // 以来此Date 对象表示毫秒数 long dayOfMillisecond = 86400000;// 一天的毫秒数 long monthOfDay = 30; currentTime = new Date(now - dayOfMillisecond * monthOfDay); String current = formatter.format(currentTime); return current; } public static void main(String[] args) { System.out.println(DateUtil.getTodayBeforeMonth()); }