int year = 2017;
int month = Calendar.JANUARY;
int dow = Calendar.MONDAY;
GregorianCalendar gcal = new GregorianCalendar(year, month, 1);
while (gcal.get(Calendar.DAY_OF_WEEK) != dow) {
gcal.add(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(gcal.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH)); // 5
新的java-8-api在月域中没有周的日,但您可以这样做:
int year = 2017;
int month = 1;
LocalDate ld1 =
LocalDate.of(year, month, 1).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
LocalDate ld2 =
LocalDate.of(year, month, 1).with(TemporalAdjusters.lastInMonth(DayOfWeek.MONDAY));
System.out.println(ChronoUnit.WEEKS.between(ld1, ld2) + 1); // 5
import org.joda.time.DateTimeConstants;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import java.util.Date;
public class Test {
public static int getNumberOfMondays(Date start, Date end) {
LocalDate startDate = LocalDate.fromDateFields(start);
LocalDate endDate = LocalDate.fromDateFields(end);
int days = Days.daysBetween(startDate, endDate).getDays();
int mondayCount = 0;
//Get number of full weeks: 1 week = 1 Monday
mondayCount += days / 7;
int remainder = days % 7;
if (startDate.dayOfWeek().get() == DateTimeConstants.MONDAY || startDate.dayOfWeek().get() > (startDate.dayOfWeek().get() + remainder) % 8) {
mondayCount++;
}
return mondayCount;
}
}
3条答案
按热度按时间xghobddn1#
即使是旧日历´-api尽管有其所有的缺点,但它提供了一种解决方案:
新的java-8-api在月域中没有周的日,但您可以这样做:
ulydmbyx2#
java.time文件
使用java 8及更高版本中内置的java.time类。
55ooxyrt3#
java 7+作业时间