在 Java 中获取当前周的开始和结束日期 - (星期一到星期日)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22890644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current week start and end date in Java - (MONDAY TO SUNDAY)
提问by Scorpion
Today is 2014-04-06 (Sunday).
今天是 2014-04-06(星期日)。
The output I get from using the code below is:
我使用下面的代码得到的输出是:
Start Date = 2014-04-07
End Date = 2014-04-13
This is the output I would like to get instead:
这是我想要的输出:
Start Date = 2014-03-31
End Date = 2014-04-06
How can I achieve this?
我怎样才能做到这一点?
This is the code I have completed so far:
这是我到目前为止完成的代码:
// 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);
采纳答案by ccjmne
Updated answer using Java 8
使用 Java 8 更新答案
Using Java 8and keeping the same principle as before (the first day of the week depends on your Locale
), you should consider using the following:
使用Java 8并保持与以前相同的原则(一周的第一天取决于您的Locale
),您应该考虑使用以下内容:
Obtain the first and last DayOfWeek
for a specific Locale
获取DayOfWeek
特定的第一个和最后一个Locale
final DayOfWeek firstDayOfWeek = WeekFields.of(locale).getFirstDayOfWeek();
final DayOfWeek lastDayOfWeek = DayOfWeek.of(((firstDayOfWeek.getValue() + 5) % DayOfWeek.values().length) + 1);
Query for this week's first and last day
查询本周的第一天和最后一天
LocalDate.now(/* tz */).with(TemporalAdjusters.previousOrSame(firstDayOfWeek)); // first day
LocalDate.now(/* tz */).with(TemporalAdjusters.nextOrSame(lastDayOfWeek)); // last day
Demonstration
示范
Consider the following class
:
考虑以下几点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);
}
}
We can demonstrate its usage as follows:
我们可以演示它的用法如下:
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
Original Java 7 answer (outdated)
原始 Java 7 答案(过时)
Simply use:
只需使用:
c.setFirstDayOfWeek(Calendar.MONDAY);
Explanation:
解释:
Right now, your first day of weekis set on Calendar.SUNDAY
. This is a setting that depends on your Locale
.
现在,您一周中的第一天设置为Calendar.SUNDAY
。这是一个取决于您的设置Locale
。
Thus, a betteralternative would be to initialise your Calendar
specifying the Locale
you're interested in.
For example:
因此,更好的选择是初始化您Calendar
指定的Locale
您感兴趣的。
例如:
Calendar c = GregorianCalendar.getInstance(Locale.US);
... would give you your currentoutput, while:
...会给你你当前的输出,而:
Calendar c = GregorianCalendar.getInstance(Locale.FRANCE);
... would give you your expectedoutput.
...会给你你预期的输出。
回答by Aman Agnihotri
Well, looks like you got your answer. Here's an add-on, using java.timein Java 8 and later. (See Tutorial)
嗯,看起来你得到了答案。这是一个附加组件,在 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);
}
}
Another way of doing it, using 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);
}
}
回答by Dev
I used below method to check if a given date falls in current week
我使用下面的方法来检查给定的日期是否在本周
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;
}
回答by K1TS
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();
}
回答by Shrikant
This is what I did to get start and end date for current week.
这就是我为获取本周的开始和结束日期所做的工作。
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();
}
回答by Islam Assi
/**
* 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;
回答by Basil Bourque
tl;dr
tl;博士
Use the handy YearWeek
class from ThreeTen-Extralibrary to represent an entire week. Then ask it to determine the date for any day-of-week within that week.
使用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
The LocalDate
class represents a date-only value without time-of-day and without time zoneor offset-from-UTC.
该LocalDate
级表示没有时间的天,没有一个日期,只值时区或偏移从-UTC。
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any momentduring runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能会在运行时随时更改(!),因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。如果关键,请与您的用户确认该区域。
Specify a proper time zone namein the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 2-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。Continent/Region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。如果省略,代码读起来会变得模棱两可,因为我们不确定您是否打算使用默认值,或者您是否像许多程序员一样没有意识到这个问题。
ZoneId z = ZoneId.systemDefault() ; // Get JVM's current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
或指定日期。您可以通过数字设置月份,对于 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.
Or, better, use the Month
enum objects pre-defined, one for each month of the year. Tip: Use these Month
objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year
& YearMonth
.
或者,更好的是使用Month
预定义的枚举对象,一年中的每个月都有一个。提示:Month
在整个代码库中使用这些对象而不仅仅是整数,以使您的代码更具自文档性、确保有效值并提供类型安全。同上Year
& YearMonth
。
LocalDate ld = LocalDate.of( 2014 , Month.APRIL , 6 ) ;
YearWeek
YearWeek
Your definition of a week running from Monday to Sunday matches that of the ISO 8601standard.
您对从星期一到星期日的一周的定义与ISO 8601标准的定义相符。
Add the ThreeTen-Extralibrary to your project to access the YearWeek
class representing the standard week.
将ThreeTen-Extra库添加到您的项目以访问YearWeek
代表标准周的类。
YearWeek week = YearWeek.from( ld ) ; // Determine the week of a certain date.
Or get today's week.
或者获取今天的一周。
YearWeek week = YearWeek.now( z ) ;
Get the date for any day of the week. Specify which day by using DayOfWeek
enum.
获取一周中任何一天的日期。使用DayOfWeek
枚举指定哪一天。
LocalDate firstOfWeek = week.atDay( DayOfWeek.MONDAY ) ;
LocalDate lastOfWeek = week.atDay( DayOfWeek.SUNDAY ) ;