我有以下日期时间:
Start = 15/12/2012 13:00:00
End = 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轻松完成吗?
答案 0 :(得分:6)
当然,试试这个(包含小帮助类)
过程:
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;
}
助手类:
public static class DateHelper
{
public static DateTime Min(DateTime date1, DateTime date2)
{
return (date1 < date2 ? date1 : date2);
}
}
答案 1 :(得分:1)
你可以试试这些扩展方法:
public static class SomeExtensions {
public static IEnumerable<Tuple<DateTime, DateTime>> GetIntervals(
this DateTime from,
DateTime to) {
var currentFrom = from;
var currentTo = from.AdvanceToStartOfNextMonth();
while (currentTo < to) {
yield return Tuple.Create(currentFrom, currentTo);
currentFrom = currentTo;
currentTo = currentFrom.AdvanceToStartOfNextMonth();
}
yield return Tuple.Create(currentFrom, to);
}
public static DateTime AdvanceToStartOfNextMonth(this DateTime @this) {
var newMonth = @this.Month + 1;
var newYear = @this.Year;
if (newMonth == 13) {
newMonth = 1;
newYear++;
}
return new DateTime(newYear, newMonth, 1);
}
}
然后像这样使用它们:
public class Etc {
public static void Foo() {
DateTime start = ...
DateTime stop = ....
Tuple<DateTime, DateTime>[] intervals = start.GetIntervals(stop).ToArray();
// or simply
foreach (var interval in start.GetIntervals(stop))
Console.WriteLine(interval);
}
}
修改强>
这是我刚试过的一个小测试(我觉得它看起来不错):
class Program {
static void Main(string[] args) {
DateTime start = DateTime.Now.Subtract(TimeSpan.FromDays(170));
DateTime stop = DateTime.Now;
foreach (var interval in start.GetIntervals(stop))
Console.WriteLine(interval);
Console.ReadKey(intercept: true);
}
}
并产生了这些结果(在控制台应用程序中):
END OF EDIT