我需要能够(在一周中的任何一天)捕获即将到来的星期一日期。如果这个语法在星期一运行,我需要以mm.dd.yyyy的格式捕获下一个星期一的日期。我知道如何以该格式捕捉日期,但我将如何捕捉即将到来的星期一?
答案 0 :(得分:1)
这是一个微不足道的问题。一个简单的循环可以做到,但可能有一堆更优化的解决方案:
namespace ConsoleApplication1
{
using System;
internal class Program
{
private static void Main(string[] args)
{
var arbitraryDate = DateTime.Today;
do
{
arbitraryDate = arbitraryDate.AddDays(1);
}
while (arbitraryDate.DayOfWeek != DayOfWeek.Monday);
Console.WriteLine(arbitraryDate.ToString("MM.dd.yyyy"));
}
}
}
答案 1 :(得分:0)
您可以使用通用扩展方法:
/// <summary>
/// Returns the first occurrence of the specified weekday following (or on) the current System.DateTime object.
/// </summary>
/// <param name="currentDate">The current date</param>
/// <param name="dayOfWeek">The weekday to find</param>
/// <param name="includeCurrentDate">Include the current date as a valid result</param>
/// <returns>The first date of the weekday after (or on) the current System.DateTime object.</returns>
public static DateTime NextWeekday(this DateTime currentDate, DayOfWeek dayOfWeek, bool includeCurrentDate)
{
int daysInWeek = 7;
int offset = includeCurrentDate ? 0 : 1;
int days = (dayOfWeek - currentDate.AddDays(offset).DayOfWeek + daysInWeek) % daysInWeek;
return currentDate.AddDays(days + offset);
}