繁体   English   中英

获取C#中某个DateTime的星期一和星期日

[英]Get the Monday and Sunday for a certain DateTime in C#

我有一个例如日期“ 2010-11-09,星期二

现在我想得到星期一和星期日的日期时间,即上述日期。

你会怎么做?

这可能是你所追求的:

 DateTime date = DateTime.Today;

 // lastMonday is always the Monday before nextSunday.
 // When date is a Sunday, lastMonday will be tomorrow.     
 int offset = date.DayOfWeek - DayOfWeek.Monday;     
 DateTime lastMonday = date.AddDays(-offset);
 DateTime nextSunday = lastMonday.AddDays(6);

编辑:因为lastMonday并不总是顾名思义(见评论),所以下面的单行可能更重要:

 DateTime nextSunday = date.AddDays(7 - (int) date.DayOfWeek);

如果使用条件方法,这很容易

if (v_datetime.DayOfWeek== DayOfWeek.Sunday)
{
return true;
}

if (v_datetime.DayOfWeek== DayOfWeek.Monday)
{

}
/// <summary>
/// Returns the day that is the specific day of week of the input day.
/// </summary>
/// <param name="input">The input day.</param>
/// <param name="dayOfWeek">0 is Monday, 6 is Sunday.</param>
/// <returns></returns>
public static DateTime GetDayOfWeekOfSpecific(DateTime input, int dayOfWeek)
{
    if(input.DayOfWeek == DayOfWeek.Sunday)
    {
        dayOfWeek -= 7;
    }
    // lastMonday is always the Monday before nextSunday.
    // When today is a Sunday, lastMonday will be tomorrow.     
    int offset = input.DayOfWeek - DayOfWeek.Monday;
    DateTime lastMonday = input.AddDays(-offset);
    DateTime nextDayOfWeek = lastMonday.AddDays(dayOfWeek);
    return nextDayOfWeek;
}

像这样的东西,当然你想在DateTime.MaxValue之前的某个点断开循环,但这应该做:

  DateTime dt = DateTime.Parse("2010-11-09, Thuesday");


        while (dt < DateTime.MaxValue) 
        {

            if(dt.DayOfWeek == DayOfWeek.Sunday || dt.DayOfWeek == DayOfWeek.Monday)
                Console.WriteLine(dt.ToString());
            dt.AddDays(1);
        }

DateTime Monday = DateTime.Now.AddDays((DateTime.Now.DayOfWeek - 1)* -1)。日期;

DateTime Sunday = DateTime.Now.AddDays(7 -DateTime.Now.DayOfWeek).Date;

暂无
暂无

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

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