C# Net 计算周(可正推和逆推)
拷贝代码(方法):
/// <summary>
/// 计算周
/// </summary>
/// <param name="Time">一个时间点,用来计算周(必须有年月日)</param>
/// <param name="WeekCount">推测的周数量</param>
/// <param name="Add">是正推(加)还是负推(减)</param>
/// <param name="ThisWeek">是否包含此时间点所在的周</param>
/// <returns></returns>
public static List<TimeWeek> GetTimeWeek(DateTime Time, int WeekCount, bool Add, bool ThisWeek)
{
List<TimeWeek> timeWeeks = new List<TimeWeek>();
TimeWeek week = new TimeWeek();
week.Week = ConvertWeekOfYear(Time);
int dayOfTheWeek = (int)Time.DayOfWeek;
int CountLength = dayOfTheWeek == ? : dayOfTheWeek;
//如果包含当前周,就加入到返回列表.同时推算的周数减一
if (ThisWeek)
{
DateTime mon = Time.Date.AddDays( - CountLength);//本周一
DateTime sun = Time.Date.AddDays( - CountLength).AddDays().AddSeconds(-);//本周日
week.BeginTime = mon;
week.EndTime = sun;
timeWeeks.Add(week);
WeekCount--;
}
if (Add)
{
for (int i = ; i <= WeekCount; i++)
{
DateTime mon = Time.Date.AddDays( - CountLength + i * );//往前推的周数计算星期一
DateTime sun = Time.Date.AddDays( - CountLength + i * ).AddDays().AddSeconds(-);
TimeWeek Downweek = new TimeWeek();
Downweek.Week = ConvertWeekOfYear(mon);
Downweek.BeginTime = mon;
Downweek.EndTime = sun;
timeWeeks.Add(Downweek);
}
}
else
{
for (int i = ; i <= WeekCount; i++)
{
DateTime mon = Time.Date.AddDays( - CountLength - i * );//往回推的周数计算星期一
DateTime sun = Time.Date.AddDays( - CountLength - i * ).AddDays().AddSeconds(-);
TimeWeek upweek = new TimeWeek();
upweek.Week = ConvertWeekOfYear(mon);
upweek.BeginTime = mon;
upweek.EndTime = sun;
timeWeeks.Add(upweek);
}
}
return timeWeeks.OrderBy(t => t.BeginTime).ToList();
} /// <summary>
/// 返回指定年份的周
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static int ConvertWeekOfYear(DateTime time)
{
System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
return gc.GetWeekOfYear(time, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}
拷贝代码(自定义类):
/// <summary>
/// 时间周
/// </summary>
public class TimeWeek
{
/// <summary>
/// 第几周(从开年的1月1日计算)
/// </summary>
public int Week { get; set; }
/// <summary>
/// 这周的开始时间(一般是周一)
/// </summary>
public DateTime BeginTime { get; set; }
/// <summary>
/// 这周的结束时间(一般是周日)
/// </summary>
public DateTime EndTime { get; set; }
}