<分区>
我想使用 C# 桌面应用程序查找现在在周数上的日期。
我一直在谷歌上寻找,但没有一个符合我的需要。
如何获得一个月中的一周,如下例所示?
示例:
我想要 2014 年 1 月 6 日 = 1 月的第一周
2014 年 1 月 30 日 = 一月的第四个周
但 2014 年 2 月 1 日 = 1 月的第 4 周
2014 年 2 月 3 日是二月的第一周
<分区>
我想使用 C# 桌面应用程序查找现在在周数上的日期。
我一直在谷歌上寻找,但没有一个符合我的需要。
如何获得一个月中的一周,如下例所示?
示例:
我想要 2014 年 1 月 6 日 = 1 月的第一周
2014 年 1 月 30 日 = 一月的第四个周
但 2014 年 2 月 1 日 = 1 月的第 4 周
2014 年 2 月 3 日是二月的第一周
最佳答案
方法如下:
static int GetWeekNumberOfMonth(DateTime date)
{
date = date.Date;
DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
if (firstMonthMonday > date)
{
firstMonthDay = firstMonthDay.AddMonths(-1);
firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
}
return (date - firstMonthMonday).Days / 7 + 1;
}
测试:
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 6))); // 1
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 30))); // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 1))); // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 3))); // 1
关于c# - 获取月份的第几周 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23060121/