Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取Java中当前一周的开始和结束日期-(周一至周日)_Java_Date_Dayofweek - Fatal编程技术网

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

获取Java中当前一周的开始和结束日期-(周一至周日),java,date,dayofweek,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.getInsta

今天是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);
使用Java8更新了答案

使用<强> java 8 < />并保持与以前相同的原则(本周的第一天取决于您的代码> LoaLe>代码),您应该考虑使用以下内容:

获取特定
区域设置的第一个和最后一个
DayOfWeek
查询本周的第一天和最后一天 示范 考虑以下

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 c = GregorianCalendar.getInstance(Locale.US);
。。。将为您提供当前输出,同时:

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

。。。将给出您的预期输出。

嗯,看起来您已经得到了答案。这是一个附加组件,在Java8和更高版本中使用。(见附件)

另一种方法是使用


我使用下面的方法来检查给定的日期是否在本周内

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

这就是我所做的,以获得本周的开始和结束日期

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

tl;博士 使用ThreeTen Extra library中方便的
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
该类表示一个只包含日期的值,不包含一天中的时间,也不包含或

时区对于确定日期至关重要。在任何一个特定的时刻,世界各地的日期都因地区而异。例如,中午夜后几分钟是新的一天,而中仍然是“昨天”

如果未指定时区,JVM将隐式应用其当前默认时区。该默认值可能在运行时(!)期间出现,因此您的结果可能会有所不同。最好将所需/预期时区明确指定为参数。如果关键,请与用户确认区域

大陆/地区
的格式指定,例如
美国/蒙特利尔
非洲/卡萨布兰卡
,或
太平洋/奥克兰
。切勿使用2-4个字母的缩写,如
EST
IST
,因为它们不是真正的时区,也不是标准化的,甚至不是唯一的(!)

如果要使用JVM的当前默认时区,请请求它并将其作为参数传递。如果省略,代码将变得模棱两可,我们无法确定您是否打算使用默认值,或者您是否像许多程序员一样不知道这个问题

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
或者指定一个日期。你可以用一个数字来设置月份,1-12月的数字为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
对象,而不仅仅是一个整数,这样可以使代码更加自我记录,确保有效值,并提供更高的可用性。同上

YearWeek
你对从周一到周日的一周的定义与标准相符

将库添加到项目中以访问表示标准周的类

YearWeek week = YearWeek.from( ld ) ;  // Determine the week of a certain date.
或者是今天的一周

YearWeek week = YearWeek.now( z ) ;
获取一周中任何一天的日期。使用枚举指定哪一天


所以你想打印两个星期天的日期?哪两个?你能给出你的输入和输出的更多例子吗?基本上我只想从周一到周日开始一周。本周从2014年3月31日开始,今天是2014年4月6日这一周的结束。我知道这个月已经变了,但由于它对我的报告非常重要,我希望它像标准的印度周一样。让;再举一个例子,2014年4月的最后一周从2014年4月28日开始,到2014年5月4日结束。简言之,我想把星期一到星期天作为一个星期。没有2个星期天要打印。好的。因此,您希望打印一个星期一日期和另一个星期日日期。输入是什么?您希望打印的日期是否介于这两个日期之间?或者你想要一个打印一系列周一和周日的程序,即开始日期和结束日期?@Amanagnihorti,OP在问题标题中说,他想要最新的。我假设这是文字,您使用的是现在遗留的、麻烦的旧日期时间类,被java.time类取代。另一个问题:堆栈溢出不仅仅是一个代码段库。提供一些关于你的答案与其他答案不同的讨论。解释你的代码示例是如何工作的。好吧,默认情况下,一周从星期天开始到星期一。所以,如果我选择日历。星期天,它属于下周。如果我想得到日历。星期一,它会告诉我下周的星期一。为了纠正这个错误,我从7天的周一开始删减。编辑你的答案以提供更多讨论。代码的另一个主要问题是忽略了时区这一关键问题。而且,真的,是时候放弃
Calendar
类的血腥混乱,学习java.time了。使用java.time,这项工作要容易得多。请参阅Aman Agnihotri的。您使用的是麻烦的旧日期时间类,这些类现在是遗留的,被java.time类取代。另一个问题:堆栈溢出不仅仅是一个代码段库。提供一些关于你的答案与其他答案不同的讨论。解释你的代码示例是如何工作的。为什么不删掉第一个代码示例,然后用
TemporalAdjuster
演示第二个代码示例呢?我认为第一个没有什么好处。我建议展示一种更好的实践,即始终为
LocalDate.now(z)
指定时区(
ZoneId
object),而不是隐式地依赖JVM?
/**
 * 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;
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.
ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;
ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
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.
LocalDate ld = LocalDate.of( 2014 , Month.APRIL , 6 ) ;
YearWeek week = YearWeek.from( ld ) ;  // Determine the week of a certain date.
YearWeek week = YearWeek.now( z ) ;
LocalDate firstOfWeek = week.atDay( DayOfWeek.MONDAY ) ;
LocalDate lastOfWeek = week.atDay( DayOfWeek.SUNDAY ) ;