获取每月的C#周 [英] Get week of month C#
本文介绍了获取每月的C#周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用c#桌面应用程序查找日期是星期几。
I want to find a date are now on week number with c# desktop Application.
我一直在Google上搜索,但都不符合我的需求。
I've been looking on google, but none that fit my needs.
如何在一个月内得到一个星期,如下例所示?
How do I get a week in a month as the example below?
示例:
我想要2014年1月6日= 1月的第一周
I want January 6, 2014 = the first week of January
2014年1月30日=一月的第四周
January 30, 2014 = fourth week
of January
但2014年2月1日= 1月的第4周
but 1 February 2014 = week 4 in January
,2014年2月3日是2月的第一周
and 3 February 2014 was the first week in February
推荐答案
这里是方法:
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#周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文