如何把一个时间段按月拆分
比如有个时间段 2013-6-8 -》2013-7-8
我想拆分为
2013-6-8 2013-6-30
2013-7-1 2013-7-8
//DateTime s_d = Convert.ToDateTime(startdate);
//DateTime e_d = Convert.ToDateTime(enddate);
//for (; s_d < e_d; )
//{
// Response.Write(s_d.ToString("yyyy-MM-dd"));
// Response.Write(s_d.AddMonths(1)
//}
帮顶!
[解决办法]
DateTime dtstatrt = new DateTime(2013,06,08);
DateTime dtstatrtDay = dtstatrt.AddMonths(1);//月份加1
//取出开始月最后一天
DateTime dtstatrtEndDay = Convert.ToDateTime(dtstatrtDay.Year.ToString() + "-" + dtstatrtDay.Month.ToString() + "-" + "1").AddDays(-1);
TimeSpan ts = dtstatrtEndDay - dtstatrt;
var test = string.Empty;
for(int i=1;i<ts.Days+1;i++)
{
test += dtstatrt.AddDays(i).ToShortDateString()+"\r\n";
}
MessageBox.Show(test);
//赋值
List<DateTime> lst = new List<DateTime>();
lst.Add(new DateTime(2013, 9, 30, 00, 30, 00));
lst.Add(new DateTime(2013, 10, 1, 00, 31, 01));
lst.Add(new DateTime(2013, 10, 30, 00, 40, 01));
//分段
var query = from t in lst.AsEnumerable()
group t by t.ToString("yyyyMMddHHmi").Substring(0, 6) into g
select new
{
_date = g.Key,
_lst = g.ToList<DateTime>()
};
//显示
StringBuilder buider = new StringBuilder();
foreach (var vq in query)
{
foreach (var item in vq._lst)
{
buider.Append(vq._date + " " + item + "\n");
}
}
MessageBox.Show(buider.ToString());
string BeginDate = "2013-06-08";
string EndDate = "2014-10-18";
if (Convert.ToDateTime(BeginDate) > Convert.ToDateTime(EndDate))
{
MessageBox.Show("开始日期大于结束日期!!");
return;
}
if (BeginDate.Substring(0,7).Equals(EndDate.Substring(0,7)))
{
textBox1.Clear();
textBox1.AppendText(BeginDate + " ~ " + EndDate);
return;
}
textBox1.Clear();
textBox1.AppendText(BeginDate + " ~ " + Convert.ToDateTime(BeginDate.Substring(0, 8) + "01").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd") + "\n");
int i = 1;
while (Convert.ToDateTime(BeginDate.Substring(0, 8) + "01").AddMonths(i) < Convert.ToDateTime(EndDate.Substring(0, 8) + "01"))
{
textBox1.AppendText(Convert.ToDateTime(BeginDate.Substring(0, 8) + "01").AddMonths(i).ToString("yyyy-MM-dd") + " ~ " + Convert.ToDateTime(BeginDate.Substring(0, 8) + "01").AddMonths(i + 1).AddDays(-1).ToString("yyyy-MM-dd") + "\n");
i++;
}
textBox1.AppendText(Convert.ToDateTime(BeginDate.Substring(0, 8) + "01").AddMonths(i).ToString("yyyy-MM-dd") + " ~ " + EndDate + "\n");
StringBuilder sbuider = new StringBuilder();
DateTime dt1 = Convert.ToDateTime("2013-6-8");
DateTime dt2 = Convert.ToDateTime("2013-10-02");
int i = 0;
for (; i < dt2.Month - dt1.Month; i++ )
{
string start = dt1.AddMonths(i).AddDays(-dt1.AddMonths(i).Day + 1).ToString();
string end = dt1.AddMonths(i).AddMonths(1).AddDays(-dt1.AddMonths(i).Day).ToString();
sbuider.Append(start + " " + end + "\n");
}
if (i != 0)
{
sbuider.Append(dt2.AddDays(-dt2.Day + 1).ToString() + " " + dt2.ToString());
}
MessageBox.Show(sbuider.ToString());