Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

java - 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?

LocalDate today = LocalDate.now();
LocalDate nextWed = ???
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...