给定C#中的一周数,我如何获得该周的开始和结束日期?

时间:2018-05-08 16:04:09

标签: c#

我想编写一个函数,该函数在一年内获得一个周数,并返回该周的开始日期。另一个获取周数的函数,并返回该周的结束日期。

伪代码:

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

如何计算这些日期?

This question is in PHP并没有帮助我。 this question gets the week number of the month也是this。我有一年中的周数。

1 个答案:

答案 0 :(得分:2)

它并不漂亮,Zohar Peled的评论是非常有效的,但这适用于正常的" (因为缺少一个更好的词)日历。 (IE:没有本地化,没什么特别的)这应该提供足够的基础来实现。

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