gpt4 book ai didi

java - 获取两个日期之间的完整 "monday to sunday"周

转载 作者:行者123 更新时间:2023-12-01 22:42:32 27 4
gpt4 key购买 nike

看看你能不能帮我。我想获取两个日期 d1 和 d2 之间的周数(从星期一开始到星期日结束)。假设 d2 早于 d1。这部分代码已经编程并可以运行。我现在的问题是我无法正确编写周程序。这就是我现在所做的:

public static void getFullWeeks(Calendar d1, Calendar d2){
int Weeks = 0;
Calendar date2 = d2;
Calendar addWeek = GregorianCalendar.getInstance();
addWeek.setTime(date2.getTime());
addWeek.add(Calendar.DATE, 6);

while(addWeek.before(d1) || addWeek.equals(d1)){
if(date2.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
Weeks++;
}
date2.add(Calendar.DATE,1);
}

System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ Weeks);
}

但是输出是“0 周”,因此程序无法运行。怎么了?我没有遇到该错误,并且无法找到该问题的有效解决方案。

谢谢!!

最佳答案

在没有外部库的 Java 8 中,您可以执行如下操作:

*编辑以说明从周一开始的一周

// TechTrip - ASSUMPTION d1 is earlier than d2
// leave that for exercise
public static long getFullWeeks(Calendar d1, Calendar d2){
// In Java the week starts on Sunday from an integral perspective
// public final static int SUNDAY = 1;
// SEQUENTIAL UP TO
// public final static int SATURDAY = 7;

// make the starting date relative to the Monday we need to calculate from
int dayOfStartWeek = d1.get(Calendar.DAY_OF_WEEK);

// IF we have a partial week we should add an offset that moves the start
// date UP TO the next Monday to simulate a week starting on Monday
// eliminating partial weeks from the calculation
// NOTE THIS METHOD WILL RETURN NEGATIVES IF D1 < D2 after adjusting for
// offset
if (dayOfStartWeek == Calendar.SUNDAY) {
// add an offset of 1 day because this is a partial week
d1.add(Calendar.DAY_OF_WEEK, 1);
} else if (dayOfStartWeek != Calendar.MONDAY){
// add an offset for the partial week
// Hence subtract from 9 accounting for shift by 1
// and start at 1
// ex if WEDNESDAY we need to add 9-4 (WED Int Val) = 5 days
d1.add(Calendar.DAY_OF_WEEK, 9 - dayOfStartWeek);
}

Instant d1i = Instant.ofEpochMilli(d1.getTimeInMillis());
Instant d2i = Instant.ofEpochMilli(d2.getTimeInMillis());

LocalDateTime startDate = LocalDateTime.ofInstant(d1i, ZoneId.systemDefault());
LocalDateTime endDate = LocalDateTime.ofInstant(d2i, ZoneId.systemDefault());

return ChronoUnit.WEEKS.between(startDate, endDate);
}

主要内容如下:

public static void main(String[] args) {
Calendar d1 = Calendar.getInstance();
Calendar d2 = Calendar.getInstance();
d2.add(Calendar.WEEK_OF_YEAR, 6);
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ getFullWeeks(d1, d2));
}

如果开始日期是星期一,则输出如下:

两个日期之间的周数(从星期一到星期日)为:6

注意,我没有将日期 d2 分配给 d1,使其成为相同的引用。在这种情况下,您将得到 0。

*ChronoUnit 采用 Temporal,它只是日期、时间或偏移量。它们必须是同一类型。时间可以用加号和减号来操纵。

关于java - 获取两个日期之间的完整 "monday to sunday"周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25923648/

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