简体   繁体   English

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

[英]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. 这个问题在PHP中 ,对我没有帮助。 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. 它不是很漂亮,并且Zohar Peled的评论非常有效,但这适用于“正常”(缺少更好的单词)日历。 (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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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