且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JSR-310中查找下一个星期的一天

更新时间:2023-01-17 07:59:41

答案取决于您对下周三的定义; - )



JSR-310使用 TemporalAdjusters class。



第一个选项是 next()

  LocalDate input = LocalDate 。现在(); 
LocalDate nextWed = input.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

第二个选项是 nextOrSame()

 LocalDate input = LocalDate.now(); 
LocalDate nextWed = input.with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));

这两种不同取决于输入日期的星期几。



如果输入日期为2014-01-22(星期三),则:




  • next()将返回2014-01-29,一周后

  • nextOrSame()将返回2014-01-22,与输入相同



如果输入日期为2014-01-20(a星期一)然后:




  • next()将返回2014-01-22

  • nextOrSame()将返回2014-01-22



ie。 next()总是返回一个更晚的日期,而 nextOrSame()将返回输入日期,如果它匹配。 p>

请注意,两个选项看起来都比静态导入更好:

  LocalDate nextWed1 = input.with(next(WEDNESDAY)); 
LocalDate nextWed2 = input.with(nextOrSame(WEDNESDAY));

TemporalAdjusters 还包括匹配的 previous() previousOrSame()方法。


Given a JSR-310 object, such as LocalDate, how can I find the date of next Wednesday (or any other day-of-week?

LocalDate today = LocalDate.now();
LocalDate nextWed = ???

The answer depends on your definition of "next Wednesday" ;-)

JSR-310 provides two options using the TemporalAdjusters class.

The first option is next():

LocalDate input = LocalDate.now();
LocalDate nextWed = input.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

The second option is 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:

  • next() will return 2014-01-29, one week later
  • nextOrSame() will return 2014-01-22, the same as the input

If the input date is 2014-01-20 (a Monday) then:

  • next() will return 2014-01-22
  • nextOrSame() will return 2014-01-22

ie. next() always returns a later date, whereas nextOrSame() will return the input date if it matches.

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.