简体   繁体   English

在 c# 中获取一个月后的下一个给定日期

[英]Get next given day after a month in c#

How can I get the next particular day after a month in c#, for example if today is Monday I need to get the first Monday after 1 month from now, but in more generic way, for example if today is 17/11/2021 which is Wednesday I need to get the first Wednesday after a month from now I am using this function but it will return for next week and not next month如何在 c# 中获得一个月后的下一个特定日期,例如,如果今天是星期一,我需要从现在开始 1 个月后的第一个星期一,但以更通用的方式,例如,如果今天是 2021 年 11 月 17 日是星期三我需要从现在开始一个月后的第一个星期三我正在使用这个 function 但它将在下周而不是下个月返回

public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
    {
        // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
        int daysToAdd = ((int)day - (int)start.DayOfWeek + 7) % 7;
        return start.AddDays(daysToAdd);
    }

Add a month, instead of a week to the start date:在开始日期添加一个月,而不是一周:

public static DateTime GetSameDayAfterMonth(DateTime start)
{
    var compare = start.AddMonths(1);
    // The % 7 ensures we end up with a value in the range [0, 6]
    int daysToAdd = ((int)start.DayOfWeek - (int)compare.DayOfWeek) % 7;
    return compare.AddDays(daysToAdd);
}

Example:例子:

var dayInNextMonth = GetSameDayAfterMonth(DateTime.Parse("2021-11-17")); // 2021-12-15

var weekday = dayInNextMonth.DayOfWeek; // Wednesday

Typical month has 30 or 31 days, however, the next same day of week will be after either 28 ( 4 * 7 ) or 35 ( 5 * 7 ) days.典型的月份有3031天,但是,一周中的下一个同一天将在28 ( 4 * 7 ) 或35 ( 5 * 7 ) 天之后。 We need a compromise .我们需要妥协 Let for February add 28 days and for all the other months add 35 days:February28天,其他月份加35天:

public static DateTime GetSameDayAfterMonth(DateTime start) =>
  start.AddDays((start.AddMonths(1) - start).TotalDays < 30 ? 28 : 35);

Sure, you can elaborate other rules: say, when after adding 28 days we are still in the same month ( 1 May + 28 days == 29 May ) we should add 35 :当然,您可以详细说明其他规则:例如,当添加28天后我们仍然在同一个月(5 月1 May + 28 days == 29 May )时,我们应该添加35

public static DateTime GetSameDayAfterMonth(DateTime start) =>
  start.AddDays(start.Month == start.AddDays(28).Month ? 35 : 28);

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

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