我想用c#桌面应用程序找到一个星期号的日期。
我一直在谷歌上搜索,但没有一个符合我的需求。
我如何在一个月内获得一周的时间,如下例所示?
示例:
我想要2014年1月6日=1月的第一周
2014年1月30日= 1月的第四个week
但2014年2月1日=1月第4周
2014年2月3日是2月的第一周
下面是方法:
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
public static int GetWeekNumber(DateTime dt)
{
CultureInfo curr= CultureInfo.CurrentCulture;
int week = curr.Calendar.GetWeekOfYear(dt, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
return week;
}
我想这就是你想要的:
public static int GetWeekOfMonth(DateTime date)
{
DateTime beginningOfMonth = new DateTime(date.Year, date.Month, 1);
while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
date = date.AddDays(1);
return (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;
}
作者:David M Mortonhttp://social.msdn.microsoft.com/Forums/vstudio/en-US/bf504bba-85cb-492d-a8f7-4ccabdf882cb/get-week-number-for-month