java获取本周所有日期,和本周第一天和最后一天,和上周所有日期,和上周第一天和上周最后一天

2020-09-11 教育 87阅读
import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;public class Main {private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");public static void main(String args[]) {Date d = new Date();// 月初System.out.println("月初" + sdf.format(getMonthStart(d)));// 月末System.out.println("月末" + sdf.format(getMonthEnd(d)));Date date = getMonthStart(d);Date monthEnd = getMonthEnd(d);while (!date.after(monthEnd)) {System.out.println(sdf.format(date));date = getNext(date);}}private static Date getMonthStart(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);int index = calendar.get(Calendar.DAY_OF_MONTH);calendar.add(Calendar.DATE, (1 - index));return calendar.getTime();}private static Date getMonthEnd(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.MONTH, 1);int index = calendar.get(Calendar.DAY_OF_MONTH);calendar.add(Calendar.DATE, (-index));return calendar.getTime();}private static Date getNext(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.DATE, 1);return calendar.getTime();}} 这是一个月的你改改就能写出上个月的了吧
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com