0

I want to write a function that gets a week number in a year, and returns the start date of that week. Also another function that gets the week number, and returns the end date of that week.

Pseudocode:

public DateTime GetSaturdayDateOfWeek(int weekNumberInYear)
{
    // calculations, that finds the Saturday of that week, 00:00:00 of midnight
    return DateTime.Now;
}

public DateTime GetFriddayDateOfWeek(int weekNumberInYear)
{
    // calculations, that finds the Friday of that week, 23:59:59
    return DateTime.Now;
}

How can I calculate these dates?

This question is in PHP and doesn't help me. Also this question gets the week number of the month. I have the week number in the year.

  • 3
    Week start and end are culture specific. Also, week number is somewhat ambiguous - if the week starts on Monday, and January 1st was Thursday, does January 6th (first Tuesday of the year) belong to the first or second week of the year? Not to mention that every year starts on a different weekday then the year before... – Zohar Peled May 08 '18 at 16:08
  • @ZoharPeled Relevant in answering those questions: https://stackoverflow.com/questions/5791919/retrieve-first-day-of-week-and-calendarweekrule-from-environment – Rotem May 08 '18 at 16:26

1 Answers1

2

It's not pretty, and Zohar Peled's comment is very valid, but this works for a "normal" (for the lack of a better word) calendar. (IE: No localization, nothing special) This should provide a sufficient base to go from.

public DateTime GetSaturdayDateOfWeek(int weekNumberInYear)
{
    var myDate = new DateTime(DateTime.Now.Year, 1, 1);
    myDate = myDate.AddDays((weekNumberInYear -1)* 7);
    if (myDate.DayOfWeek < DayOfWeek.Saturday)
    {
        myDate = myDate.AddDays(DayOfWeek.Saturday - myDate.DayOfWeek);
    }
    if (myDate.DayOfWeek > DayOfWeek.Saturday)
    {
        myDate = myDate.AddDays(myDate.DayOfWeek - DayOfWeek.Saturday);
    }
    return myDate;
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195
billgeek
  • 46
  • 5