[英]Split a date range into several ranges?
我有一个开始日期和一个结束日期(采用sql server datetime格式)。 我想将其分为几个范围,即几对开始和结束日期值。 注意-我有.NET 3.5和Visual Studio 2008。
例如。 S =2005。E= 2010,块大小= 1年。 生成的巴黎= 2005-06、06-07、07-08、08-2010
块可以是任意天数/月数。 我将代码放在主方法之后的SO帖子中,但出现一些错误。 发布-将日期范围拆分为日期范围块
代码-
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;
}
yield return Tuple.Create(start, end);
}
我得到两个错误:
'CodeHere.csproj.ScriptMain.SplitDateRange(System.DateTime,System.DateTime,int)'的主体不能是迭代器块,因为'IEnumerable
和:
当前上下文中不存在名称“ Tuple”
您正在尝试使用System.Tuple<T1, T2>
,它仅在.NET 4中引入。您正在使用.NET 3.5,因此该结构不可用。 我建议您创建自己的DateRange
类型,该类型封装开始和结束DateTime
,然后返回IEnumerable<DateRange>
。
要么升级到.NET 4或4.5 ...
这是.NET 3.5的处理方式。 正如其他人所说的,.NET 3.5中不存在元组。
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main(string[] args)
{
var myDateTime = new DateTime(2013, 10, 29);
var myEndDateTime = new DateTime(2014, 10, 29);
var result = SplitDateRange(myDateTime, myEndDateTime, 10);
var file = new System.IO.StreamWriter("c:\\dateFile.txt");
foreach (var item in result)
{
file.WriteLine("StartDate: {0}, EndDate: {1}", item.StartDateTime, item.EndDateTime);
}
file.Close();
}
public static IEnumerable<SplitDateTime> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return new SplitDateTime(start, chunkEnd);
start = chunkEnd;
}
yield return new SplitDateTime(start, end);
}
}
public class SplitDateTime
{
public SplitDateTime(DateTime startDateTime, DateTime endDateTime)
{
StartDateTime = startDateTime;
EndDateTime = endDateTime;
}
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.