如何在C#中获取下一个特定日期的日期

时间:2018-04-26 00:58:45

标签: c# date datetime

如何在C#中获取下周一到周五或下周五到来的日期。 让我们说今天是星期三,我想得到星期五的日期。 这就是我所做的

DateTime time = DateTime.Now.Date;
DateTime NextFriday;
if (time.DayOfWeek == DayOfWeek.Wednesday)
{
    NextFriday = DateTime.Now.AddDays(2);
}

通过这种方法,我每天都会启动7个变量,并且每天都有7个条件可以找到下一个特定日期。

是否有更好更干净的代码,我可以通过该代码获取下一天的任何日期。

4 个答案:

答案 0 :(得分:1)

您应该使用支持此功能的时间库,例如NodaTime。

请参阅https://nodatime.org/1.3.x/userguide/arithmetic

上的date.Next(IsoDayOfWeek.Sunday)

这是另一种解决方案(请不要使用此功能):

DateTime F(DateTime t, DayOfWeek dayOfWeek) => t.AddDays((7 + (int)dayOfWeek - (int)t.DayOfWeek) % 7);

for (int i = 0; i < 7; i++)
    Console.WriteLine((DayOfWeek)i + " " + F(DateTime.Now, (DayOfWeek)i));

输出(于2014年4月4日星期三):

Sunday 4/29/2018 12:00:00 AM
Monday 4/30/2018 12:00:00 AM
Tuesday 5/1/2018 12:00:00 AM
Wednesday 4/25/2018 12:00:00 AM
Thursday 4/26/2018 12:00:00 AM
Friday 4/27/2018 12:00:00 AM
Saturday 4/28/2018 12:00:00 AM

答案 1 :(得分:0)

DateTime today = DateTime.Today;
DateTime nextFriday = System.Linq.Enumerable.Range(0, 6)
  .Select(i => today.AddDays(i))
  .Single(day => day.DayOfWeek == DayOfWeek.Friday);

答案 2 :(得分:0)

使用以下

public int CalculateOffset(DayOfWeek current, DayOfWeek desired) {
    // f( c, d ) = [7 - (c - d)] mod 7
    // f( c, d ) = [7 - c + d] mod 7
    // c is current day of week and 0 <= c < 7
    // d is desired day of the week and 0 <= d < 7
    int c = (int)current;
    int d = (int)desired;
    int offset = (7 - c + d) % 7;
    return offset == 0 ? 7 : offset;
}

您可以计算距所需日期的距离,然后将其添加到当前日期

DateTime now = DateTime.Now.Date;
int offset = CalculateOffset(now.DayOfWeek, DayOfWeek.Friday);
DateTime nextFriday = now.AddDays(offset);

答案 3 :(得分:0)

DayOfWeek只是介于0和6之间的枚举,因此使用模块化算法,您可以使用您感兴趣的日期与目标星期几之间的差异来计算您必须添加的天数。

快速警告,当您询问“今天”的含义时,您需要考虑感兴趣的时区。这取决于您居住的日期行的哪一侧,这意味着不同的事情。

using System;

public class Program
{

    public static DateTime NextDayForDay(DayOfWeek dayOfWeek, DateTime occurringAfter)
    {
        return occurringAfter.AddDays(((dayOfWeek - occurringAfter.DayOfWeek + 6) % 7)+1); 
    }

    public static void Main()
    {
        for (int i=0; i < 7; i++)
        {
            for (int j=0; j < 7; j++)
            {
                DayOfWeek dayOfWeek = (DayOfWeek)(((int)DayOfWeek.Sunday + j) % 7);

                DateTime test = DateTime.Today.AddDays(i);
                Console.WriteLine($"{test}=>Next {dayOfWeek} is {NextDayForDay(dayOfWeek, test)}");
            }
        }   
    }
}