[英]Get the Monday and Sunday for a certain DateTime in C#
I have a for example the date " 2010-11-09, Thuesday " 我有一个例如日期“ 2010-11-09,星期二 ”
Now I want to get the datetime of the Monday and Sunday wherein lies the above stated date. 现在我想得到星期一和星期日的日期时间,即上述日期。
How would you do that? 你会怎么做?
This is probaly what you're after: 这可能是你所追求的:
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);
Edit: since lastMonday
is not always what the name suggests (see the comments), the following one-liner is probably more to the point: 编辑:因为lastMonday
并不总是顾名思义(见评论),所以下面的单行可能更重要:
DateTime nextSunday = date.AddDays(7 - (int) date.DayOfWeek);
It's easily if you use a conditional method 如果使用条件方法,这很容易
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;
}
Something like this, of course you would want to break from the loop at some point before the DateTime.MaxValue, but this should do: 像这样的东西,当然你想在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).Date; DateTime Monday = DateTime.Now.AddDays((DateTime.Now.DayOfWeek - 1)* -1)。日期;
DateTime Sunday = DateTime.Now.AddDays(7 -DateTime.Now.DayOfWeek).Date; DateTime Sunday = DateTime.Now.AddDays(7 -DateTime.Now.DayOfWeek).Date;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.