java获取指定日期所在周的第一天和最后一天

来源:互联网 发布:秘鲁地震预警软件 编辑:程序博客网 时间:2024/04/29 20:46

java获取指定日期所在周的第一天和最后一天

第一种方法

public static String getFirstAndLastOfWeek(String dataStr) throws ParseException {        Calendar cal = Calendar.getInstance();        cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(dataStr));        int d = 0;        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {            d = -6;        } else {            d = 2 - cal.get(Calendar.DAY_OF_WEEK);        }        cal.add(Calendar.DAY_OF_WEEK, d);        // 所在周开始日期        String data1 = new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime());        cal.add(Calendar.DAY_OF_WEEK, 6);        // 所在周结束日期        String data2 = new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime());        return data1 + "-" + data2;    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

第二种方法

public static String getFirstAndLastOfWeek(int date) throws ParseException {        Date InputDate = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(20140101));        Calendar cDate = Calendar.getInstance();        cDate.setFirstDayOfWeek(Calendar.MONDAY);        cDate.setTime(InputDate);        Calendar firstDate = Calendar.getInstance();        firstDate.setFirstDayOfWeek(Calendar.MONDAY);        firstDate.setTime(InputDate);        Calendar lastDate = Calendar.getInstance();        lastDate.setFirstDayOfWeek(Calendar.MONDAY);        lastDate.setTime(InputDate);        if (cDate.get(Calendar.WEEK_OF_YEAR) == 1 && cDate.get(Calendar.MONTH) == 11) {            firstDate.set(Calendar.YEAR, cDate.get(Calendar.YEAR) + 1);            lastDate.set(Calendar.YEAR, cDate.get(Calendar.YEAR) + 1);        }        int typeNum = cDate.get(Calendar.WEEK_OF_YEAR);        System.out.println(typeNum);        firstDate.set(Calendar.WEEK_OF_YEAR, typeNum);        firstDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);        // 所在周开始日期        String beginDate = new SimpleDateFormat("yyyy/MM/dd").format(firstDate.getTime());        System.out.println(beginDate);        lastDate.set(Calendar.WEEK_OF_YEAR, typeNum);        lastDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);        // 所在周结束日期        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(lastDate.getTime());        System.out.println(endDate);        return beginDate + "-" + endDate;    }
阅读全文
0 0
原创粉丝点击