0

I have a need for a project that I'm working on to query an API for a given date range - in this case a week, e.g.:

Sunday (2019-06-02T00:00:00Z) - Saturday (2019-06-08T23:59:59Z)

So, what I'm given through user input is a week and a year, e.g.:

Week - 23

Year - 2019

Is there a good way using Java 8 to determine what days that corresponds to?

Edit: I looked around but didn't find a recent solution to this problem, the closest thing I saw was using JodaTime. I was wondering if there was a better/more modern approach to this problem?

Pr0pagate
  • 199
  • 2
  • 12
  • What exactly is your definition of a week and a week number? – Basil Bourque Jun 11 '19 at 16:10
  • A week by US Locale, i.e. Sunday - Saturday. And a week corresponding to the 52 weeks in a year. – Pr0pagate Jun 11 '19 at 16:17
  • Tip: Learn about the Half-Open approach to edging a span-of-time. Your week should run up to, but not include, the first moment of the following Sunday. By trying to determine the last moment of the Saturday, you are missing the moments of the infinitely divisible last second such as 2019-06-08T23:59:59.063Z. – Basil Bourque Jun 11 '19 at 16:17
  • 2
    Does week # 1 contain the first day of the year? Or the first Sunday if the year? Or the first full week of days populated only by days of the new year and no days from the prior year? Also, note that some definitions of a week number result in 53 weeks in a year, not always 52. I suggest considering the use of the standard ISO 8601 week definition. – Basil Bourque Jun 11 '19 at 16:21
  • All this has been discussed many times on Stack Overflow. Search to learn more. – Basil Bourque Jun 11 '19 at 16:23

1 Answers1

1

Since you know that a week has seven days, you know that the numerical day of the year is the week * 7 which in this case is 23 * 7.

You can use the LocalDate.ofYear(year, dayOfYear) method to get the start date, then add 6 days to get the end of the week.

LocalDate startDate = LocalDate.ofYearDay(2019, 23 * 7);
LocalDate endDate = startDate.plusDays(6);

LocalDateTime startDateTime = LocalDateTime.of(startDate, LocalTime.of(0, 0, 0));
LocalDateTime endDateTime = startDateTime.plusDays(7).minusSeconds(1);

System.out.println(startDate.getDayOfWeek() + "(" + startDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ss'Z'")) + ")");
System.out.println(endDate.getDayOfWeek() + "(" + endDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ss'Z'")) + ")");

output:

MONDAY(2019-06-10T12:00:00Z)

SUNDAY(2019-06-16T11:59:59Z)

nLee
  • 1,320
  • 2
  • 10
  • 21
  • IMHO it’s too handheld, and it will not work correctly under every week numbering scheme (I don’t know how the questioner assumes that weeks are numbered). – Ole V.V. Jun 11 '19 at 19:32