今天在CSDN看到一个关于取当前日期是在一年中的第几周的帖子,上了头条推荐,里面解决方法的思路,是先取得该年第一天是星期几,然后取当前日期的DayOfYear再除以7,同时用DayOfYear对7取余,从而得到当前日期是一年中的第几周。
这种方法不但麻烦,而且效率低,其实C#里有GregorianCalendar这样一个类,只需要两行代码,就可以很轻松的完成这个任务的,只是很多人不知道,或是遗忘了。
using System.Globalization;
GregorianCalendar gc = new GregorianCalendar();
int weekOfYear = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
GregorianCalendar gc = new GregorianCalendar();
int weekOfYear = gc.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
写成通用的方法,获取某一日期是该年中的第几周
using System.Globalization;
/// <summary>
/// 获取某一日期是该年中的第几周
/// </summary>
/// <param name="dt">日期</param>
/// <returns>该日期在该年中的周数</returns>
private int GetWeekOfYear(DateTime dt)
{
GregorianCalendar gc = new GregorianCalendar();
return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}
/// <summary>
/// 获取某一日期是该年中的第几周
/// </summary>
/// <param name="dt">日期</param>
/// <returns>该日期在该年中的周数</returns>
private int GetWeekOfYear(DateTime dt)
{
GregorianCalendar gc = new GregorianCalendar();
return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}
以前还在CSDN上遇到这样一个问题,就是计算某一年有多少周,同样可以用这个类的方法来解决
using System.Globalization;
/// <summary>
/// 获取某一年有多少周
/// </summary>
/// <param name="year">年份</param>
/// <returns>该年周数</returns>
private int GetWeekAmount(int year)
{
DateTime end = new DateTime(year, 12, 31); //该年最后一天
System.Globalization.GregorianCalendar gc = new GregorianCalendar();
return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday); //该年星期数
}
/// <summary>
/// 获取某一年有多少周
/// </summary>
/// <param name="year">年份</param>
/// <returns>该年周数</returns>
private int GetWeekAmount(int year)
{
DateTime end = new DateTime(year, 12, 31); //该年最后一天
System.Globalization.GregorianCalendar gc = new GregorianCalendar();
return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday); //该年星期数
}
来自: http://www.cnblogs.com/supers/archive/2008/11/17/1335182.html