C# combox加入时间段 yyyy/mm/dd-yyyy/mm/dd
2015-10-26 21:35
429 查看
要做一个下拉菜单,按周为一个时间段,我是用一个容器存时间段和对应的日期,并对日期做一定的处理,详细代码如下:
</pre><pre name="code" class="csharp"><pre name="code" class="csharp">//键值对容器 ,时间段为string类型,对应一周的日期存入对应的数组 Dictionary list = new Dictionary(); #region 绑定时间段 /// /// 键值对,获得时间段和具体日期 /// private void GetTime() { string[] s = null ; //开始时间 string a = "2014/12/28"; //时间段 sd~ed DateTime sd; DateTime ed = Convert.ToDateTime(a); DateTime nowtime=DateTime.Now; int com_index=0; string[] save_value = new string[7];//暂存日期数组 for (int i = 0; i < 53; i++) { sd = ed.AddDays(1); ed = sd.AddDays(6); string dt = sd.ToString("yyyy/MM/dd") + "-" + ed.ToString("yyyy/MM/dd"); if (s == null)//这种写法可以避免加入日期重复 { s = new string[7]; for (int j = 0; j < 7; j++) { s[j] = sd.AddDays(j).ToShortDateString(); } } if (s != null) { save_value = s; } s = null; list.Add(dt, save_value); //如果当前日期在某个时间段之间,记住 if (DateTime.Compare(nowtime, sd) > 0 && DateTime.Compare(ed, nowtime) > 0) { com_index = i; } } //绑定conbox comtime.DataSource = list.Keys.ToList(); // 默认显示本周 comtime.SelectedIndex = com_index; } #endregion
[code]