日期:2014-05-17 浏览次数:20485 次
private void button1_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("year"); dt.Columns.Add("month"); dt.Columns.Add("day"); dt.Columns.Add("date"); dt.Columns.Add("week"); dt.Columns.Add("weeks"); dt.Columns.Add("isrestday"); DateTime beginTime = new DateTime(2012,01,01); DateTime endTime = new DateTime(2017, 01, 01); TimeSpan days = endTime - beginTime; for (int i = 0; i < days.Days; i++) { DateTime date = beginTime.AddDays(i); DataRow dr = dt.NewRow(); dr["year"] = date.Year; dr["month"] = date.Month; dr["day"] = date.Day; dr["date"] = date.Date; dr["week"] = date.DayOfWeek; dr["weeks"] = GetWeekIndex(date.Date); if (date.DayOfWeek==DayOfWeek.Saturday||date.DayOfWeek==DayOfWeek.Sunday) { dr["isrestday"] = "0"; } else { dr["isrestday"] = "1"; } dt.Rows.Add(dr); } this.dataGridView1.DataSource = dt; } /// <summary> /// 获取当前日期是一年中的第几周,如果12月31号与下一年的1月1好在同一个星期则算下一年的第一周 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static int GetWeekIndex(DateTime dt) { //确定此时间在一年中的位置 int dayOfYear = dt.DayOfYear; //当年第一天 DateTime tempDate = new DateTime(dt.Year, 1, 1); //确定当年第一天 int tempDayOfWeek = (int)tempDate.DayOfWeek; tempDayOfWeek = tempDayOfWeek == 0 ? 7 : tempDayOfWeek; //确定星期几 int index = (int)dt.DayOfWeek; index = index == 0 ? 7 : index; //当前周的范围 DateTime retStartDay = dt.AddDays(-(index - 1)); DateTime retEndDay = dt.AddDays(7 - index); //确定当前是第几周 int weekIndex = (int)Math.Ceiling(((double)dayOfYear + tempDayOfWeek - 1) / 7); if (retStartDay.Year < retEndDay.Year) { weekIndex = 1; } return weekIndex; }
------解决方案--------------------
declare @start datetime declare @end datetime set @start = '2012-01-01' set @end = '2014-01-01' while ( @start < @end ) begin print str(year(@start )) + str( month( @start) ) + str( day( @start ) ) +' ' + CONVERT(varchar (10), @s