Given a week number in C#, how can I gain start and end dates of that week?

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.

Upvotes: 0

Views: 244

Answers (1)

billgeek
billgeek

Reputation: 76

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;
}

Upvotes: 2

Related Questions