Java获取上周的日期列表

时间:2018-08-06 05:37:36

标签: java android date

尝试根据指定的日期获取上一周的日期列表时遇到问题。这是我的代码:

        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd");
        Date refDate = null;
        try {
            refDate = formatter.parse("Sun Aug 05");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date[] days = reservationViewModel.getDaysOfWeek(refDate, Calendar.getInstance().getFirstDayOfWeek());
        for (Date day : days) {
            // display            
        }

获取日期列表的代码:

public static Date[] getDaysOfWeek(Date refDate, int firstDayOfWeek) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(refDate);
    calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
    Date[] daysOfWeek = new Date[7];
    for (int i = 0; i < 7; i++) {
        daysOfWeek[i] = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    return daysOfWeek;
}

但是,我得到的结果是:

Sun Aug 02
Mon Aug 03
Tue Aug 04
Wed Aug 05
Thu Aug 06
Fri Aug 07
Sat Aug 08

日期都错了。应该是从7月29日到8月4日。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

使用Calendar.WEEK_OF_YEAR将时间移至给定日期之前的1周。代码就像calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) - 1);

所以您的情况应该是

public static Date[] getDaysOfWeek(Date refDate, int firstDayOfWeek) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(refDate);
    calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
    calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) - 1);
    Date[] daysOfWeek = new Date[7];
    for (int i = 0; i < 7; i++) {
        daysOfWeek[i] = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    return daysOfWeek;
}

获取前7天

public static Date[] getPrevious7Days(Date refDate) {
    Calendar calendar = Calendar.getInstance();
    int currentYear = calendar.get(Calendar.YEAR);
    calendar.setTime(refDate);
    calendar.set(Calendar.YEAR, currentYear);
    calendar.add(Calendar.DAY_OF_MONTH, -7);

    Date[] daysOfWeek = new Date[7];
    for (int i = 0; i < 7; i++) {
        daysOfWeek[i] = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    return daysOfWeek;
}

它将打印为

Sun Jul 29 00:00:00 IST 2018
Mon Jul 30 00:00:00 IST 2018
Tue Jul 31 00:00:00 IST 2018
Wed Aug 01 00:00:00 IST 2018
Thu Aug 02 00:00:00 IST 2018
Fri Aug 03 00:00:00 IST 2018
Sat Aug 04 00:00:00 IST 2018