//計算當前日期是本月的第幾周
private int GetWeekNumInMonth(DateTime daytime)
{
int dayInMonth = daytime.Day;
//本月第一天
DateTime firstDay = daytime.AddDays(1 - daytime.Day);
//本月第一天是周几
int weekday = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.DayOfWeek;
//本月第一周有几天
int firstWeekEndDay = 7 - (weekday - 1);
//当前日期和第一周之差
int diffday = dayInMonth - firstWeekEndDay;
diffday = diffday > 0 ? diffday : 1;
//当前是第几周,如果整除7就减一天
int WeekNumInMonth = ((diffday % 7) == 0
? (diffday / 7 - 1)
: (diffday / 7)) + 1 + (dayInMonth > firstWeekEndDay ? 1 : 0);
return WeekNumInMonth;
}
/// <summary>
/// 計算前week周的起始日期
/// </summary>
/// <param name="week">需要計算的前week周(0為當前周,1為前一周.....)</param>
/// <param name="dt_StartTime">周一日期</param>
/// /// <param name="dt_StartTime">周日日期</param>
/// <returns></returns>
public void GetWeekStartEndDate(DateTime dt, int week, out DateTime dt_StartTime, out DateTime dt_EndTime)
{
int n_DayOfWeek = int.Parse(dt.DayOfWeek.ToString("d"));
dt_StartTime = DateTime.Parse(dt.AddDays(-n_DayOfWeek - week * 7 + 1).ToString("yyyy/MM/dd"));
dt_EndTime = DateTime.Parse(dt.AddDays(-n_DayOfWeek - (week - 1) * 7).ToString("yyyy/MM/dd"));
if (dt_EndTime > dt)
{
dt_EndTime = dt;
}
}
//計算時間所對應在本年的周別
public int GetWeekOfYear(DateTime dt)
{
int firstWeekEnd = 7 - Convert.ToInt32(DateTime.Parse(dt.Year + "-1-1").DayOfWeek);
int currentDay = dt.DayOfYear;
return Convert.ToInt32(Math.Ceiling((currentDay - firstWeekEnd) / 7.0)) + 1;
}
//計算本周的起始日期
public DateTime GetCurrentWeekStartDate(DateTime dt)
{
int n_DayOfWeek = int.Parse(dt.DayOfWeek.ToString("d"));
return DateTime.Parse(dt.AddDays(-n_DayOfWeek + 1).ToString("yyyy/MM/dd"));
}