Java - 如何计算每周的第一天和最后一天

2022-09-02 11:09:16

我正在尝试创建一个如下所示的每周日历:http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html

如何计算每周日期?例如,本周是:

6月7日(星期一至星期日
),6月8日,6月9日,6月10日,6月11日,6月12日,6月13日


答案 1

我想这符合你的意愿:

// Get calendar set to current date and time
Calendar c = Calendar.getInstance();

// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
    System.out.println(df.format(c.getTime()));
    c.add(Calendar.DATE, 1);
}

答案 2

使用Java 8中的新日期和时间API,您可以执行以下操作:

LocalDate now = LocalDate.now();

// determine country (Locale) specific first day of current week
DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));

// determine last day of current week
DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));

// Print the dates of the current week
LocalDate printDate = startOfCurrentWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
for (int i=0; i < 7; i++) {
    System.out.println(printDate.format(formatter));
    printDate = printDate.plusDays(1);
}

推荐