[英]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.