gpt4 book ai didi

.net - 在 .NET 中计算月份中的第几周

转载 作者:行者123 更新时间:2023-12-03 07:06:41 25 4
gpt4 key购买 nike

.NET 库是否有一种简单的方法来返回给定日期的周数?例如,输入Year = 2010,Month = 1,Day = 25,应输出5作为周数。

我发现的最接近的是Calendar.GetWeekOfYear,它几乎就在那里。

Java 有一个日期字符串格式“W”,它返回月份中的星期,但我在 .NET 中看不到任何等效的内容。

最佳答案

没有内置方法可以执行此操作,但这里有一个扩展方法可以为您完成这项工作:

static class DateTimeExtensions {
static GregorianCalendar _gc = new GregorianCalendar();
public static int GetWeekOfMonth(this DateTime time) {
DateTime first = new DateTime(time.Year, time.Month, 1);
return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
}

static int GetWeekOfYear(this DateTime time) {
return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
}
}

用法:

DateTime time = new DateTime(2010, 1, 25);
Console.WriteLine(time.GetWeekOfMonth());

输出:

5

您可以根据需要更改GetWeekOfYear

关于.net - 在 .NET 中计算月份中的第几周,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136487/

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