[英]Find next occurrence of a day-of-week in JSR-310
Given a JSR-310 object, such as LocalDate
, how can I find the date of next Wednesday (or any other day-of-week?给定 JSR-310 对象,例如LocalDate
,如何找到下周三(或任何其他星期几?
LocalDate today = LocalDate.now();
LocalDate nextWed = ???
The answer depends on your definition of "next Wednesday" ;-)答案取决于您对“下周三”的定义;-)
JSR-310 provides two options using the TemporalAdjusters class. JSR-310 使用TemporalAdjusters类提供了两个选项。
The first option is next() :第一个选项是next() :
LocalDate input = LocalDate.now();
LocalDate nextWed = input.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
The second option is nextOrSame() :第二个选项是nextOrSame() :
LocalDate input = LocalDate.now();
LocalDate nextWed = input.with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));
The two differ depending on what day-of-week the input date is.两者根据输入日期是星期几而有所不同。
If the input date is 2014-01-22 (a Wednesday) then:如果输入日期是 2014-01-22(星期三),则:
next()
will return 2014-01-29, one week later next()
将在一周后返回 2014-01-29nextOrSame()
will return 2014-01-22, the same as the input nextOrSame()
将返回 2014-01-22,与输入相同If the input date is 2014-01-20 (a Monday) then:如果输入日期是 2014-01-20(星期一),则:
next()
will return 2014-01-22 next()
将返回 2014-01-22nextOrSame()
will return 2014-01-22 nextOrSame()
将返回 2014-01-22 ie. IE。 next()
always returns a later date, whereas nextOrSame()
will return the input date if it matches. next()
总是返回较晚的日期,而nextOrSame()
如果匹配则返回输入日期。
Note that both options look much better with static imports:请注意,使用静态导入,这两个选项看起来要好得多:
LocalDate nextWed1 = input.with(next(WEDNESDAY));
LocalDate nextWed2 = input.with(nextOrSame(WEDNESDAY));
TemporalAdjusters
also includes matching previous()
and previousOrSame()
methods. TemporalAdjusters
还包括匹配previous()
和previousOrSame()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.