实现点击按钮更改周,并获取本周,上周,下周对应的具体日期
借鉴了一些网上的方法
/// <summary> /// 定义 /// </summary> DateTime beginDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Monday, 0);//默认开始时间为本周周一 DateTime endDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Sunday, 1); //默认结束时间为本周周日,因为周日为每周第一天,所以本周周日为下周第一天 /// <param name="dt">指定日期</param> /// <param name="weekday">需要获取周几</param> /// <param name="Number">控制获取哪周(-1:上周; 0:本周; 1:下周; 2:下下周)</param> private static DateTime getWeekUpOfDate(DateTime dt, DayOfWeek weekday, int Number) { int wd1 = (int)weekday; int wd2 = (int)dt.DayOfWeek; return wd2 == wd1 ? dt.AddDays(7 * Number) : dt.AddDays(7 * Number - wd2 + wd1);//周日为每周第一天 }
1 #region 更改周 按钮事件 2 /// <summary> 3 /// 本周 4 /// </summary> 5 private void btnThisWeek_Click(object sender, EventArgs e) 6 { 7 beginDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Monday, 0);//本周周一 8 endDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Sunday, 1); //下周周日 9 DateBind(); 10 11 } 12 13 /// <summary> 14 /// 上周 15 /// </summary> 16 private void btnLastWeek_Click(object sender, EventArgs e) 17 { 18 beginDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Monday, -1);//上周周一 19 endDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Sunday, 0); //本周周日 20 DateBind(); 21 22 } 23 24 /// <summary> 25 /// 下周 26 /// </summary> 27 private void btnNextWeek_Click(object sender, EventArgs e) 28 { 29 beginDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Monday, 1);//下周周一 30 endDate = getWeekUpOfDate(DateTime.Now, DayOfWeek.Sunday, 2); //下下周周日 31 DateBind();
32 33 } 34 #endregion
1 /// <summary> 2 /// 绑定每天对应的日期 3 /// </summary> 4 private void DateBind() 5 { 6 DateTime beginTime = beginDate; 7 DateTime endTime = endDate; 8 DateTime[] times = GetDateTime(beginTime, endTime);//查出星期一到星期日的日期 9 if (times.Length > 0) 10 { 11 TextBox1.Text= times[0].ToShortDateString(); //星期一的日期 12 TextBox2.Text = times[1].ToShortDateString(); //星期二的日期 13 TextBox3.Text = times[2].ToShortDateString(); //星期三的日期 14 TextBox4.Text = times[3].ToShortDateString(); //星期四的日期 15 TextBox5.Text = times[4].ToShortDateString(); //星期五的日期 16 TextBox6.Text = times[5].ToShortDateString(); //星期六的日期 17 TextBox7.Text = times[6].ToShortDateString(); //星期日的日期 18 } 19 20 }
1 /// <summary> 2 /// 计算每周每天对应的日期 3 /// </summary> 4 private DateTime[] GetDateTime(DateTime beginTime, DateTime endTime) 5 { 6 List<DateTime> timeList = new List<DateTime>(); 7 for (; beginTime <= endTime; beginTime = beginTime.AddDays(1))//周一到周日的日期 8 { 9 timeList.Add(beginTime); 10 11 } 12 DateTime[] times = timeList.ToArray(); 13 return times; 14 }