在Java中获取当前周开始和结束日期 - (周一至周日)

时间:2014-04-06 06:15:26

标签: java date dayofweek

今天是2014-04-06(星期日)。

我使用以下代码得到的输出是:

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);

7 个答案:

答案 0 :(得分:21)

使用Java 8

更新了答案

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

获取特定DayOfWeek

的第一个和最后一个Locale
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.SUNDAY上。这个设置取决于您的Locale

因此,更好替代方案是初始化Calendar,指定您感兴趣的Locale
例如:

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

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

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

...会为您提供预期的输出。

答案 1 :(得分:13)

好吧,看起来你得到了答案。这是一个加载项,在Java 8及更高版本中使用java.time。 (见Tutorial

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);
  }
}

另一种方法,使用temporal adjusters

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);
  }
}

答案 2 :(得分:2)

这是我为获取本周的开始和结束日期所做的工作。

public static Date getWeekStartDate() {
    Calendar calendar = Calendar.getInstance();
    while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        calendar.add(Calendar.DATE, -1);
    }
    return calendar.getTime();
}

public static Date getWeekEndDate() {
    Calendar calendar = Calendar.getInstance();
    while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        calendar.add(Calendar.DATE, 1);
    }
    calendar.add(Calendar.DATE, -1);
    return calendar.getTime();
}

答案 3 :(得分:0)

我使用以下方法检查给定日期是否属于当前周

public boolean isDateInCurrentWeek(Date date) 
{
        Date currentWeekStart, currentWeekEnd;

        Calendar currentCalendar = Calendar.getInstance();
        currentCalendar.setFirstDayOfWeek(Calendar.MONDAY);
        while(currentCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY)
        {
            currentCalendar.add(Calendar.DATE,-1);//go one day before
        }
        currentWeekStart = currentCalendar.getTime();

        currentCalendar.add(Calendar.DATE, 6); //add 6 days after Monday
        currentWeekEnd = currentCalendar.getTime();

        Calendar targetCalendar = Calendar.getInstance();
        targetCalendar.setFirstDayOfWeek(Calendar.MONDAY);
        targetCalendar.setTime(date);


        Calendar tempCal = Calendar.getInstance();
        tempCal.setTime(currentWeekStart);

        boolean result = false;
        while(!(tempCal.getTime().after(currentWeekEnd)))
        {
            if(tempCal.get(Calendar.DAY_OF_YEAR)==targetCalendar.get(Calendar.DAY_OF_YEAR))
            {
                result=true;
                break;
            }
            tempCal.add(Calendar.DATE,1);//advance date by 1
        }

        return result;
    }

答案 4 :(得分:0)

Calendar privCalendar = Calendar.getInstance();
Date fdow, ldow;
int dayofWeek = privCalendar.get ( Calendar.DAY_OF_WEEK );
Date fdow, ldow;

                    if( dayofWeek == Calendar.SUNDAY ) {

                        privCalendar.add ( Calendar.DATE, -1 * (dayofWeek -
                                Calendar.MONDAY ) - 7 );

                        fdow = privCalendar.getTime();

                        privCalendar.add( Calendar.DATE, 6 );

                        ldow = privCalendar.getTime();
                    } else {

                        privCalendar.add ( Calendar.DATE, -1 * (dayofWeek -
                                Calendar.MONDAY ) );

                        fdow = privCalendar.getTime();

                        privCalendar.add( Calendar.DATE, 6 );

                        ldow = privCalendar.getTime();
                    }

答案 5 :(得分:0)

/**
 * Get the date of the first day in the week of the provided date
 * @param date A date in the interested week
 * @return The date of the first week day
 */
public static Date getWeekStartDate(Date date){
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.DAY_OF_WEEK, getFirstWeekDay());
    return cal.getTime();
}

/**
 * Get the date of the last day in the week of the provided date
 * @param date A date in the interested week
 * @return The date of the last week day
 */
public static Date getWeekEndDate(Date date){
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, 6);// last day of week
    return cal.getTime();
}

Date now = new Date(); // any date
Date weekStartDate = getWeekStartDate(now);
Date weekEndDate = getWeekEndDate(now);

// if you don't want the end date to be in the future
if(weekEndDate.after(now))
    weekEndDate = now;

答案 6 :(得分:0)

tl; dr

使用 ThreeTen-Extra 库中方便的YearWeek类表示一整周。然后要求它确定该周中任一星期几的日期。

org.threeten.extra.YearWeek          // Handy class representing a standard ISO 8601 week. Class found in the *ThreeTen-Extra* project, led by the same man as led JSR 310 and the *java.time* implementation.
.now(                                // Get the current week as seen in the wall-clock time used by the people of a certain region (a time zone). 
    ZoneId.of( "America/Chicago" ) 
)                                    // Returns a `YearWeek` object.
.atDay(                              // Determine the date for a certain day within that week.
    DayOfWeek.MONDAY                 // Use the `java.time.DayOfWeek` enum to specify which day-of-week.
)                                    // Returns a `LocalDate` object.

LocalDate

LocalDate类表示没有日期,没有time zoneoffset-from-UTC的仅日期值。

时区对于确定日期至关重要。在任何给定时刻,日期都会在全球范围内变化。例如,Paris France午夜之后的几分钟是新的一天,而Montréal Québec仍然是“昨天”。

如果未指定时区,则JVM隐式应用其当前的默认时区。该默认值可能在运行时(!)期间change at any moment,因此您的结果可能会有所不同。最好将您的期望/期望时区明确指定为参数。如果紧急,请与您的用户确认区域。

Continent/Region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用2-4个字母的缩写,例如ESTIST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

如果要使用JVM的当前默认时区,请提出要求并作为参数传递。如果省略,代码将变得难以理解,因为我们不确定您是否打算使用默认值,还是像许多程序员一样不知道该问题。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

或指定日期。您可以用数字设置月份,一月至十二月的理智编号为1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

或者更好的是,使用预定义的Month枚举对象,每年的每个月使用一个。提示:在整个代码库中使用这些Month对象,而不是仅使用整数,可以使您的代码更具自记录性,确保有效值并提供type-safetyYearYearMonth的同上。

LocalDate ld = LocalDate.of( 2014 , Month.APRIL , 6 ) ;

YearWeek

您对从星期一到星期日的一周的定义与ISO 8601标准的定义匹配。

ThreeTen-Extra库添加到您的项目中,以访问代表标准周的YearWeek类。

YearWeek week = YearWeek.from( ld ) ;  // Determine the week of a certain date.

或者获得今天的星期。

YearWeek week = YearWeek.now( z ) ;

获取星期几的日期。通过使用DayOfWeek枚举来指定哪一天。

LocalDate firstOfWeek = week.atDay( DayOfWeek.MONDAY ) ;
LocalDate lastOfWeek = week.atDay( DayOfWeek.SUNDAY ) ;