java 如何在Java中获得过去的星期天和即将到来的星期天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4536230/
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
How to get the past Sunday and the coming Sunday in Java?
提问by Frank
I asked How to detect if a date is within this or next week in Java?but the answers were confusing, so now I think if I can find the past Sunday and the coming Sunday, any day in between is this week, and any day between the coming Sunday and the Sunday after that is next week, am I correct ?
我问如何在 Java 中检测日期是否在本周或下周内?但是答案令人困惑,所以现在我想如果我能找到过去的星期天和下一个星期天,中间的任何一天都是本周,而下一个星期日和之后的星期天之间的任何一天都是下周,我说得对吗?
So my new question is : How to get the past Sunday and the coming Sunday in Java ?
所以我的新问题是:如何在 Java 中获得过去的星期天和即将到来的星期天?
回答by Bobby Eickhoff
java.time
时间
Briefly:
简要地:
LocalDate.now().with( next( SUNDAY ) )
See this code run live at IdeOne.com.
Details
细节
I thought I'd add a Java 8 solution for posterity. Using LocalDate
, DayOfWeek
, and TemporalAdjuster
implementation found in the TemporalAdjusters
class.
我想我会为后代添加一个 Java 8 解决方案。使用LocalDate
、DayOfWeek
和TemporalAdjuster
在TemporalAdjusters
类中找到的实现。
final LocalDate today = LocalDate.of(2015, 11, 20);
final LocalDate nextSunday = today.with(next(SUNDAY));
final LocalDate thisPastSunday = today.with(previous(SUNDAY));
This approach also works for other temporal classes like ZonedDateTime
.
这种方法也适用于其他时间类,如ZonedDateTime
.
import
import
As written, it assumes the following static imports:
正如所写,它假定以下静态导入:
import java.time.LocalDate;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.next;
import static java.time.temporal.TemporalAdjusters.previous;
回答by Frank
How about this :
这个怎么样 :
Calendar c=Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
DateFormat df=new SimpleDateFormat("EEE yyyy/MM/dd HH:mm:ss");
System.out.println(df.format(c.getTime())); // This past Sunday [ May include today ]
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime())); // Next Sunday
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime())); // Sunday after next
The result :
结果 :
Sun 2010/12/26 00:00:00
Sun 2011/01/02 00:00:00
Sun 2011/01/09 00:00:00
Any day between the first two is this week, anything between the last two is next week.
前两天之间的任何一天都是本周,后两天之间的任何一天都是下周。
回答by Jonathan B
First, don't use the Date/Time package from Java. There is a much better utility package called Joda-Time- download that and use it.
首先,不要使用 Java 的 Date/Time 包。有一个更好的实用程序包,称为Joda-Time- 下载并使用它。
To determine if your time is in this week, last week, or any week at all, do this:
要确定您的时间是在本周、上周还是任何一周,请执行以下操作:
- Create two Interval objects - one for last week and one for this week
- Use the contains( long ) method to determine which interval holds the date you are looking for.
- 创建两个 Interval 对象 - 一个用于上周,一个用于本周
- 使用 contains( long ) 方法来确定哪个间隔包含您正在查找的日期。
There are several cool ways you can create two back to back weeks. You could set up a Duration of one week, find the start time for the first week, and just create two Intervals based on that start time. Feel free to find any other way that works for you - the package has numerous ways to get to what you want.
有几种很酷的方法可以创建连续两周。您可以将 Duration 设置为一周,找到第一周的开始时间,然后根据该开始时间创建两个间隔。随意找到适合您的任何其他方式 - 该软件包有多种方式可以满足您的需求。
EDIT:
编辑:
Joda-Time can be downloaded here, and here is an example of how Joda would do this:
Joda-Time 可以在此处下载,以下是 Joda 如何执行此操作的示例:
// Get the date today, and then select midnight of the first day of the week
// Joda uses ISO weeks, so all weeks start on Monday.
// If you want to change the time zone, pass a DateTimeZone to the method toDateTimeAtStartOfDay()
DateTime midnightToday = new LocalDate().toDateTimeAtStartOfDay();
DateTime midnightMonday = midnightToday.withDayOfWeek( DateTimeConstants.MONDAY );
// If your week starts on Sunday, you need to subtract one. Adjust accordingly.
DateTime midnightSunday = midnightMonday.plusDays( -1 );
DateTime midnightNextSunday = midnightSunday.plusDays( 7 );
DateTime midnightSundayAfter = midnightNextSunday.plusDays( 7 );
Interval thisWeek = new Interval( midnightSunday, midnightNextSunday );
Interval nextWeek = new Interval( midnightNextSunday, midnightSundayAfter );
if ( thisWeek.contains( someDate.getTime() )) System.out.println("This week");
if ( nextWeek.contains( someDate.getTime() )) System.out.println("Next week");
回答by robert_x44
Without using a better time/date package...
不使用更好的时间/日期包...
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
Calendar now = new GregorianCalendar();
Calendar start = new GregorianCalendar(now.get(Calendar.YEAR),
now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH) );
while (start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
start.add(Calendar.DAY_OF_WEEK, -1);
}
Calendar end = (Calendar) start.clone();
end.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(df.format(now.getTime()) );
System.out.println(df.format(start.getTime()) );
System.out.println(df.format(end.getTime()) );
If today is Sunday, it is considered the start of the time period. If you want a period of this week and next week (as it sounds from your question), you can substitute 14 instead of 7 in the end.add(...) line. The times are set to midnight for comparison of another object falling between start and end.
如果今天是星期日,则将其视为时间段的开始。如果您想要本周和下周的一段时间(从您的问题中听起来),您可以在 end.add(...) 行中替换 14 而不是 7。时间设置为午夜,用于比较落在开始和结束之间的另一个对象。
回答by Soubhab Pathak
Given bellow next Sunday code and you can easily figure out how to find past Sunday.
给出下周日代码,您可以轻松找出如何找到过去的周日。
private static void nextSunday() throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
int days = Calendar.SUNDAY - weekday;
if (days < 0)
{
days += 7;
}
calendar.add(Calendar.DAY_OF_YEAR, days);
System.out.println(sdf.format(calendar.getTime()));
}
回答by Max
I recently developed Lamma Datewhich is designed to solve this use case:
我最近开发了Lamma Date,旨在解决这个用例:
Date today = new Date(2014, 7, 1); // assume today is 2014-07-01
Date previousSunday = today.previousOrSame(DayOfWeek.SUNDAY); // 2014-06-29
Date nextSunday = today.next(DayOfWeek.SUNDAY); // 2014-07-06
回答by Eric
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html
I recommend Calendar.get(Calendar.DAY_OF_WEEK)
我推荐 Calendar.get(Calendar.DAY_OF_WEEK)
回答by mhaller
You could try to work with the Calendar.WEEK_OF_YEAR
field, which gives you the numeric representation of the week within the current year.
您可以尝试使用该Calendar.WEEK_OF_YEAR
字段,它为您提供当前年份中一周的数字表示。
@Test
public void testThisAndNextWeek() throws Exception {
GregorianCalendar lastWeekCal = new GregorianCalendar(2010,
Calendar.DECEMBER, 26);
int lastWeek = lastWeekCal.get(Calendar.WEEK_OF_YEAR);
GregorianCalendar nextWeekCal = new GregorianCalendar(2011,
Calendar.JANUARY, 4);
int nextWeek = nextWeekCal.get(Calendar.WEEK_OF_YEAR);
GregorianCalendar todayCal = new GregorianCalendar(2010,
Calendar.DECEMBER, 27);
int currentWeek = todayCal.get(Calendar.WEEK_OF_YEAR);
assertTrue(lastWeekCal.before(todayCal));
assertTrue(nextWeekCal.after(todayCal));
assertEquals(51, lastWeek);
assertEquals(52, currentWeek);
// New Year.. so it's 1
assertEquals(1, nextWeek);
}
回答by Guillaume Chevalier
My Solution:
我的解决方案:
LocalDate date = ...;
LocalDate newWeekDate = date.plusDays(1);
while (newWeekDate.getDayOfWeek() != DayOfWeek.SATURDAY &&
newWeekDate.getDayOfWeek() != DayOfWeek.SUNDAY) {
newWeekDate = date.plusDays(1);
}