c# - 如何获取给定日期的N个月后同一天和同一周的日期

标签 c# datetime

我正在寻找一些逻辑来获取给定日期的同一天(例如:星期三)和同一周(例如:第一或第二...)的 N 个月后的日期。

例如:12-06-2013(星期三和六月第三周)是指定日期。 在这里,我在给定日期的基础上添加了 3 个月。 结果应该是2013年8月14日(星期三和8月第三周)。

如果您需要更多说明,请告诉我。

提前致谢。

最佳答案

好的,所以我个人会使用我的 Noda Time库来做到这一点。使用 DateTime 完全可以做到这一点,但我个人发现它更难。我还鼓励您使用 Noda Time一般来说,当然,作为更好的日期/时间 API。所以我会有这样的东西:

static LocalDate AddMonthsPreserveWeekDayAndWeek(LocalDate start, int months)
{
    // This isn't the week of month in the "normal" sense; it's the nth
    // occurrence of this weekday.
    int week = ((start.DayOfMonth - 1) / 7) + 1;

    // This will usually give the same day of month, but truncating where
    // necessary
    LocalDate monthsAdded = start.AddMonths(months);
    LocalDate endOfPreviousMonth = monthsAdded.AddDays(-monthsAdded.Day);

    // Get to the first occurrence of the right day-of-week
    LocalDate firstRightDay = endOfPreviousMonth.Next(start.IsoDayOfWeek);

    // Usually this will be right - but it might overflow to the next month,
    // in which case we can just rewind by a week.
    LocalDate candidate = firstRightDay.PlusWeeks(week - 1);
    return candidate.Month == firstRightDay.Month ? candidate
                                                  : candidate.PlusWeeks(-1);
}

不过,这完全未经测试 - 您绝对应该进行一堆单元测试(最好是在包含此代码之前编写)来测试您感兴趣的各种边缘情况。

关于c# - 如何获取给定日期的N个月后同一天和同一周的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17059492/

相关文章:

mysql - 使用 TIMESTAMP 数据类型选择特定日期的行

sql - 如何比较 SQL Server 中的时间?

c# - 使用 WebClient 进行 JSON 序列化?

c# - ASP.NET Core 2 中的依赖注入(inject)问题

c# - 在 C# 中从 Msi 中的自定义操作强制重启

python - 将日期函数应用于列以提取日期属性

c# - 将日期从 View 传递到 Controller mvc/c#

python - 如何在 Python 中获取 UTC 日期字符串?

c# - .NET - 用单个 using 语句替换嵌套的 using 语句

c# - 如何在字符串中写入上标并使用 MessageBox.Show() 显示?