我想使用 c# 桌面应用程序查找现在在周数上的日期。
我一直在谷歌上寻找,但没有一个符合我的需求。
如下例所示,如何获得一个月中的一周?
例子:
我想要 2014 年 1 月 6 日 = 1 月的第一周
2014 年 1 月 30 日 = 第四次week
一月的
但 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;
}
Test:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)