gpt4 book ai didi

c# - 获取两个日期时间之间的所有月份和年份

转载 作者:行者123 更新时间:2023-11-30 19:09:51 26 4
gpt4 key购买 nike

我需要的是获得有关如何在两个日期之间获取月名年的逻辑。

Dictionary<Monthname,year> GetMonthsandYear(Datetime d1,Datetime d2) 
or
List<Tuple<string,int> GetMonthsandYear(Datetime d1,Datetime d2)

示例:2013 年 1 月 1 日至 2013 年 3 月 3 日

应该返回 January-2013,february-2013,march-2013 或通过 list.reverse 的反向格式

最佳答案

如果您的实际要求是“过去 24 个月”,那就简单多了。只需从当前月份开始,获取它的第一天 - 然后迭代并添加 1 个月 24 次。

我个人会返回 IEnumerable<DateTime>而不是其他任何东西 - 您可以根据需要格式化每个元素 - 但它非常简单:

public static IEnumerable<DateTime> GetMonths(int count)
{
// Note: this uses the system local time zone. Are you sure that's what
// you want?
var today = DateTime.Today;
// Always return the 1st of the month, so we don't need to worry about
// what "March 30th - 1 month" means
var startOfMonth = new DateTime(today.Year, today.Month, 1);
for (int i = 0; i < count; i++)
{
yield return startOfMonth;
startOfMonth = startOfMonth.AddMonths(-1);
}
}

那么如果你想要一个List<string>例如,将这些值设置为“2014 年 2 月”等,您可以:

var monthYears = GetMonths(24).Select(dt => dt.ToString("MMMM yyyy"))
.ToList();

请注意 Dictionary<...>除非您真的不关心顺序,否则 是合适的 - 我怀疑您关心。您不应该依赖从 Dictionary<TKey, TValue> 返回的项目的顺序当您将其视为一个序列时 - 它并不是一个有序的集合。

关于c# - 获取两个日期时间之间的所有月份和年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21971268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com