本文介绍了拆分为月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据时间:
开始= 15/12/2012 13:00:00
结束= 16/02/2013 14:00:00
如何将其分为3部分一个月?
- 15-12-2012 13:00:00 - > 01-01-2013 00:00:00
- 01-01-2013 00:00:00 - > 01-02-2013 00:00:00
- 01-02-2013 00:00:00 - > 16-02-2013 14:00:00
总次数必须保持不变。
这可以很容易地使用LINQ吗?
解决方案
确定,尝试这个(包含小帮手类) p>
进程:
var Start = DateTime.Parse(2012年12月15日13:00:00);
var End = DateTime.Parse(2013年2月16日14:00:00);
var runningDate =开始;
while(runningDate< End)
{
var nextMonthSeed = runningDate.AddMonths(1);
var to = DateHelper.Min(new DateTime(nextMonthSeed.Year,nextMonthSeed.Month,1),End);
Console.WriteLine({0} - > {1},runningDate.ToString(dd-MM-yyyy HH:mm:ss),to.ToString(dd-MM-yyyy HH: mm:ss));
runningDate = to;
}
助手类:
public static class DateHelper
{
public static DateTime Min(DateTime date1,DateTime date2)
{
return(date1< date2 ?date1:date2);
}
}
I have the following datetimes:
Start = 15/12/2012 13:00:00
End = 16/02/2013 14:00:00
How can I split that in 3 parts for each month?
- 15-12-2012 13:00:00 -> 01-01-2013 00:00:00
- 01-01-2013 00:00:00 -> 01-02-2013 00:00:00
- 01-02-2013 00:00:00 -> 16-02-2013 14:00:00
The total timespan must remain the same.Can this easily be done with LINQ?
解决方案
sure, try this (with little helper class included)
Process:
var Start = DateTime.Parse("15 Dec 2012 13:00:00");
var End = DateTime.Parse("16 Feb 2013 14:00:00");
var runningDate = Start;
while (runningDate < End)
{
var nextMonthSeed = runningDate.AddMonths(1);
var to = DateHelper.Min(new DateTime(nextMonthSeed.Year, nextMonthSeed.Month, 1), End);
Console.WriteLine("{0} -> {1}", runningDate.ToString("dd-MM-yyyy HH:mm:ss"), to.ToString("dd-MM-yyyy HH:mm:ss"));
runningDate = to;
}
Helper class:
public static class DateHelper
{
public static DateTime Min(DateTime date1, DateTime date2)
{
return (date1 < date2 ? date1 : date2);
}
}
这篇关于拆分为月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!