Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalDate from Week and WeekYear

Tags:

c#

nodatime

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

The reverse of this:

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);
like image 238
Tom Lokhorst Avatar asked Jul 05 '12 10:07

Tom Lokhorst


1 Answers

Firstly, you should be looking at how to construct the relevant LocalDate - that's all the information you logically have if you've got a WeekYear and WeekOfWeekYear. You can then get a LocalDateTime from a LocalDate with AtMidnight if you really want - but I'd stick with LocalDate until you really need anything else, as that way you're synthesizing less information.

I don't believe we currently make this particularly simple, to be honest - although the underlying engine supports enough computations that we could add it fairly easily.

Without any changes to the API, I would suggest you'd probably be best off with something like:

  • Construct June 1st within the desired year, which should have the same WeekYear (I'm assuming you're using the ISO calendar...)
  • Get to the first day of the week (date = date.Previous(IsoDayOfWeek.Monday))
  • Work out the current week number
  • Add or subtract the right 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 terribly pleasant or efficient, but not too bad... if you find yourself wanting to do a lot of work with WeekOfWeekYear and WeekYear, please raise feature requests for the kind of thing you want to do.

EDIT: Just as an update, we now support this:

LocalDate date = LocalDate.FromWeekYearWeekAndDay(year, week, IsoDayOfWeek.Monday);
like image 133
Jon Skeet Avatar answered Oct 08 '22 01:10

Jon Skeet