在Java中获取当前周的开始和结束日期 - (周一至周日)使用 Java 8 更新的答案原始 Java 7 答案(已过时)

2022-09-01 15:03:04

今天是2014年4月6日(星期日)

我使用下面的代码获得的输出是:

Start Date = 2014-04-07
End Date = 2014-04-13

这是我想得到的输出:

Start Date = 2014-03-31
End Date = 2014-04-06

我怎样才能做到这一点?

这是我到目前为止完成的代码:

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

System.out.println("Current week = " + Calendar.DAY_OF_WEEK);

// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);

// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";

startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());

System.out.println("Start Date = " + startDate);
System.out.println("End Date = " + endDate);

答案 1

使用 Java 8 更新的答案

使用Java 8并保持与以前相同的原则(一周的第一天取决于您),您应该考虑使用以下方法:Locale

获取特定属性的第一个和最后一个DayOfWeekLocale

final DayOfWeek firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
final DayOfWeek lastDayOfWeek = DayOfWeek.of(((firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);

查询本周的第一天和最后一天

LocalDate.now(/* tz */).with(TemporalAdjusters.previousOrSame(firstDayOfWeek)); // first day
LocalDate.now(/* tz */).with(TemporalAdjusters.nextOrSame(lastDayOfWeek));      // last day

示范

请考虑以下事项:class

private static class ThisLocalizedWeek {

    // Try and always specify the time zone you're working with
    private final static ZoneId TZ = ZoneId.of("Pacific/Auckland");

    private final Locale locale;
    private final DayOfWeek firstDayOfWeek;
    private final DayOfWeek lastDayOfWeek;

    public ThisLocalizedWeek(final Locale locale) {
        this.locale = locale;
        this.firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
        this.lastDayOfWeek = DayOfWeek.of(((this.firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
    }

    public LocalDate getFirstDay() {
        return LocalDate.now(TZ).with(TemporalAdjusters.previousOrSame(this.firstDayOfWeek));
    }

    public LocalDate getLastDay() {
        return LocalDate.now(TZ).with(TemporalAdjusters.nextOrSame(this.lastDayOfWeek));
    }

    @Override
    public String toString() {
        return String.format(   "The %s week starts on %s and ends on %s",
                                this.locale.getDisplayName(),
                                this.firstDayOfWeek,
                                this.lastDayOfWeek);
    }
}

我们可以按如下方式演示它的用法:

final ThisLocalizedWeek usWeek = new ThisLocalizedWeek(Locale.US);
System.out.println(usWeek);
// The English (United States) week starts on SUNDAY and ends on SATURDAY
System.out.println(usWeek.getFirstDay()); // 2018-01-14
System.out.println(usWeek.getLastDay());  // 2018-01-20

final ThisLocalizedWeek frenchWeek = new ThisLocalizedWeek(Locale.FRANCE);
System.out.println(frenchWeek);
// The French (France) week starts on MONDAY and ends on SUNDAY
System.out.println(frenchWeek.getFirstDay()); // 2018-01-15
System.out.println(frenchWeek.getLastDay());  // 2018-01-21

原始 Java 7 答案(已过时)

只需使用:

c.setFirstDayOfWeek(Calendar.MONDAY);

解释:

现在,您一周的第一天已设置为 。此设置取决于您的 .Calendar.SUNDAYLocale

因此,更好的替代方法是初始化您感兴趣的指定。
例如:CalendarLocale

Calendar c = GregorianCalendar.getInstance(Locale.US);

...将为您提供当前输出,同时:

Calendar c = GregorianCalendar.getInstance(Locale.FRANCE);

...会给你你预期的输出。


答案 2

好吧,看起来你得到了答案。这是一个附加组件,在Java 8及更高版本中使用java.time。(请参阅教程)

import java.time.DayOfWeek;
import java.time.LocalDate;

public class MondaySunday
{
  public static void main(String[] args)
  {
    LocalDate today = LocalDate.now();

    // Go backward to get Monday
    LocalDate monday = today;
    while (monday.getDayOfWeek() != DayOfWeek.MONDAY)
    {
      monday = monday.minusDays(1);
    }

    // Go forward to get Sunday
    LocalDate sunday = today;
    while (sunday.getDayOfWeek() != DayOfWeek.SUNDAY)
    {
      sunday = sunday.plusDays(1);
    }

    System.out.println("Today: " + today);
    System.out.println("Monday of the Week: " + monday);
    System.out.println("Sunday of the Week: " + sunday);
  }
}

另一种方法是使用时间调节器

import java.time.LocalDate;

import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
import static java.time.temporal.TemporalAdjusters.previousOrSame;

public class MondaySunday
{
  public static void main(String[] args)
  {
    LocalDate today = LocalDate.now();

    LocalDate monday = today.with(previousOrSame(MONDAY));
    LocalDate sunday = today.with(nextOrSame(SUNDAY));

    System.out.println("Today: " + today);
    System.out.println("Monday of the Week: " + monday);
    System.out.println("Sunday of the Week: " + sunday);
  }
}