LocalDate from week and week

Using the NodaTime library, how can I calculate LocalDate on the first day of the week based on WeekYear week number and week number.

On the contrary:

var date = new LocalDate(2012, 1, 1); int weekYear = date.WeekYear; // 2011 int weekNr = date.WeekOfWeekYear; // 52 

Something like this fake code:

 var newDate = LocalDate.FirstDayFromWeek(weekYear, weekNr); 
+6
source share
1 answer

First, you should look at how to build the corresponding LocalDate - all the information that you logically use if you have WeekYear and WeekOfWeekYear . You can get LocalDateTime from LocalDate using AtMidnight if you want, but I would stick with LocalDate until you need something else as you synthesize less information.

I don’t think that at present we are doing this especially simply, to be honest, although the base engine supports a sufficient amount of computation, we could add it quite easily.

Without any changes to the API, I would suggest that you would probably be best off:

  • Build on June 1st for the desired year, which should have the same WeekYear (I assume you use the ISO calendar ...)
  • Get to the first day of the week ( date = date.Previous(IsoDayOfWeek.Monday) )
  • Develop the current week number
  • Add or subtract the correct number of weeks

So something like:

 public static LocalDate LocalDateFromWeekYearAndWeek(int weekYear, int weekOfWeekYear) { LocalDate midYear = new LocalDate(weekYear, 6, 1); LocalDate startOfWeek = midYear.Previous(IsoDayOfWeek.Monday); return startOfWeek.PlusWeeks(weekOfWeekYear - startOfWeek.WeekOfWeekYear); } 

Not very pleasant or effective, but not very bad ... if you want to do a lot of work with WeekOfWeekYear and WeekYear , please raise feature requests for what you want to do.

EDIT: as an update, we now support this:

 LocalDate date = LocalDate.FromWeekYearWeekAndDay(year, week, IsoDayOfWeek.Monday); 
+8
source

Source: https://habr.com/ru/post/919744/


All Articles