java中,根据指定日期显示出前n天的日期
大家好,我是雄雄,欢迎关注微信公众号:雄雄的小课堂
今天分享的是:在java中,根据指定日期显示出前n天的日期
效果如下:

大家注意观察上面的时间,我传入的时间是:2022年5月9日21:28:03,第二个参数表示前多少天的日期,我传入的是7,也就是一周。
显示的出来的日期正好是7天的日期,代码如下:
/*** 根据当前时间获取往前n天的时间*/public static List<String> getWeekDateByCurrentDate(Date currentDate,int n) {List<String> listDate = new ArrayList<>();SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");try {Calendar calendar = Calendar.getInstance();calendar.setTime(currentDate);calendar.add(Calendar.DAY_OF_MONTH, -n);for (int i = 0; i < n; i++) {listDate.add(dateFormat.format(calendar.getTime()));calendar.add(Calendar.DAY_OF_MONTH, 1);}} catch (Exception e) {e.printStackTrace();}return listDate;}
调用如下:
@Testpublic void contextLoads() {/*Long val = System.currentTimeMillis();System.out.println(val);*/List<String> dateStr = DateParseUtils.getWeekDateByCurrentDate(new Date(),7);for (String str : dateStr) {System.out.println(str);}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
