gpt4 book ai didi

Java获取上周的日期列表

转载 作者:行者123 更新时间:2023-12-02 10:56:20 28 4
gpt4 key购买 nike

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

        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日。有任何想法吗?谢谢!

最佳答案

使用 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

关于Java获取上周的日期列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701116/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com