0

Is there any way using any library to do something like this.

DateTime getStartingDate(String year, int weekNo){
    //should return the starting day of the given weekNo of the given year.
}

Ex: year = 2016 weekNo=1

DateTime returning = 3rd Jan in (Sun-Sat format) = 4th Jan in (Mon-Sun format)

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
  • 1
    Why are you accepting `year` as a string? Is your desired week numbering system precisely ISO-8601? I'd also suggest that `LocalDate` is the more appropriate return type. – Jon Skeet Jul 25 '16 at 16:34

1 Answers1

3

It seems that you want, as a starting point, the first full week that starts on a given day of week (Sunday or Monday in your example).

This could be achieved with something like this:

import static java.time.temporal.TemporalAdjusters.nextOrSame;

public static LocalDate getStartingDate(int year, int weekNo, DayOfWeek weekStart) {
  //should check that arguments are valid etc.
  return Year.of(year).atDay(1).with(nextOrSame(weekStart)).plusDays((weekNo - 1) * 7);
}

or as an alternative:

return Year.of(year).atDay(1).with(ALIGNED_WEEK_OF_YEAR, weekNo).with(nextOrSame(weekStart));

And you call it like this:

import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SUNDAY;

System.out.println(getStartingDate(2016, 1, SUNDAY)); //2016-01-03
System.out.println(getStartingDate(2016, 1, MONDAY)); //2016-01-04
assylias
  • 321,522
  • 82
  • 660
  • 783