简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM