日期:2014-05-18  浏览次数:20796 次

C#函数输入年和周,返回周所在的开始日期和结束日期
public static string GetWeekRange(int year, int weekIndex)
  {
  if (weekIndex < 1)
  {
  throw new Exception("请输入大于0的整数");
  }
  int allDays = (weekIndex - 1) * 7;
  //确定当年第一天
  DateTime firstDate = new DateTime(year, 1, 1);
  int firstDayOfWeek = (int)firstDate.DayOfWeek;
  firstDayOfWeek = firstDayOfWeek == 0 ? 7 : firstDayOfWeek;

  //周开始日
  int startAddDays = allDays + (1 - firstDayOfWeek);
  DateTime weekRangeStart = firstDate.AddDays(startAddDays);
  //周结束日
  int endAddDays = allDays + (7 - firstDayOfWeek);
  DateTime weekRangeEnd = firstDate.AddDays(endAddDays);

  if (weekRangeStart.Year > year || (weekRangeStart.Year == year && weekRangeEnd.Year > year))
  {
  throw new Exception("今年没有第" + weekIndex + "周。");
  }

   
  }

 这个函数是输入年和周,我想返回weekRangeStart, weekRangeEnd这两个值,如何调用上面这个函数,请指点


------解决方案--------------------
上面方法没有返回值。。


//周开始日
int startAddDays = allDays + (1 - firstDayOfWeek);
DateTime weekRangeStart = firstDate.AddDays(startAddDays);
//周结束日
int endAddDays = allDays + (7 - firstDayOfWeek);
DateTime weekRangeEnd = firstDate.AddDays(endAddDays);

return weekRangeStart.tostring()+" "+weekRangeEnd.tostring();


需要时直接调用这个GetWeekRange(2011,52)就可以了
返回值应该是:2011-12-25 2011-12-31
------解决方案--------------------
这是我前几天一个项目里用到时写的。给分吧哥们。我这个很实用哟

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MEETOK.Components
{
public class ToolDate
{

/// <summary>
/// 周次转化为日期范围
/// </summary>
/// <param name="ParmYear">年</param>
/// <param name="ParmWeek">周次</param>
/// <returns></returns>
public static string WeekToDate(int ParmYear, int ParmWeek)
{

int year = ParmYear, yearStart, yearEnd, monthStart, monthEnd, dayStart, dayEnd, week = ParmWeek, sum = 0;
int[] days = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int i;
sum += 7 * (week - 1);

//修正当前总天数
#region
switch (DateTime.Parse(year + "-1-1").DayOfWeek)
{
case DayOfWeek.Tuesday:
{
sum += 5;
break;
}
case DayOfWeek.Wednesday:
{
sum += 4;
break;
}
case DayOfWeek.Thursday:
{
sum += 3;
break;
}
case DayOfWeek.Friday:
{
sum += 2;
break;
}
case DayOfWeek.Saturday:
{
sum += 1;
break;
}
case DayOfWeek.Sunday:
{
//sum;