阿修--一直在自我修炼,希望能得到百年道行

湖南微软开发者俱乐部

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

今天有朋友问题我如何获取某年中第几个礼拜的时间范围,似乎以前好像记得.NET有,不过今天一查没有翻到,在google搜索到这个,希望以后能自己用上,测试已经通过。

        public static void Main()
{

DateTime date1 = GoToWeek(2012, 2);
Console.Write(date1.ToString());
Console.Read();
}

private static DateTime GoToWeek(int year, int week)
{
// use the current culture
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;

// get first day of week from culture
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;

// new empty Date (so starts 01/01/0001)
DateTime d = new DateTime();

// year starts at 1, so take away 1 from desired year to prevent going to the next one
d = d.AddYears(year - 1);

// get day January 1st falls on
int startDay = (int)d.DayOfWeek;

// get the difference between the first day of the week, and the day January 1st starts on
int difference = (int)fdow - startDay;
// if it is positive (i.e. after first day of week), take away 7
if (difference > 0)
{
difference = difference - 7;
}

// already on week 1, so add desired number of weeks - 1 * days in week
if (week > 1)
{
d = d.AddDays((week - 1) * 7 + difference);
}

return d;
}

private static int WeekOfYear(DateTime date)
{
// use the current culture
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
// use current culture's calendar
System.Globalization.Calendar cal = ci.Calendar;
// get the calendar week rule (i.e. what determines the first week in the year)
System.Globalization.CalendarWeekRule cwr = ci.DateTimeFormat.CalendarWeekRule;
// get the first day of week for the current culture
DayOfWeek fdow = ci.DateTimeFormat.FirstDayOfWeek;
// return the week
return cal.GetWeekOfYear(date, cwr, fdow);
}



posted on 2012-03-05 15:59  阿修  阅读(579)  评论(0编辑  收藏  举报