在C#中时间跨度交叉点 [英] Timespan intersection in c#

查看:264
本文介绍了在C#中时间跨度交叉点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有2日期范围。

这些日期范围可以重新psented随着时间的跨度$ P $。

我想找到一个日期范围,落在两个时间跨度内。

 范围1:2011年2月1日 -  2011年8月1日(6个月的时间跨度)
范围2:2011年5月2日 -  2011年5月28日(26天时间跨度)
 

所以在这种情况下,交叉点是5/2 / 2011-5 / 28/2011年,但范围可以移动在任一方向,(或不相交于所有在这种情况下,我会希望将所得的入库时间到0长度)

在最后,我需要的所得的交集时间跨度的开始/结束的日历日期(不只是蜱/小时/天等)

有一个优雅的方式来做到这一点在C#3.0吗?

更新

我把StriplingWarriors code和创建的方法了吧。

 私有静态DATERANGE GetIntersectionRange(DATERANGE范围1,DATERANGE范围2){
        VAR iRange =新DATERANGE();
        iRange.From = range1.From< range2.From? range2.From:range1.From;
        iRange.To = range1.To< range2.To? range1.To:range2.To;
        如果(iRange.From> iRange.To)iRange = NULL;
        返回iRange;
    }
 

解决方案

这样的事情,也许?

  VAR范围1 =新{开始= DateTime.Parse(2011年2月1日),结束= DateTime.Parse(2011年8月1日)};
VAR范围2 =新{开始= DateTime.Parse(2011年5月2日),结束= DateTime.Parse(2011年5月28日)};
VAR ISTART = range1.start< range2.start? range2.start:range1.start;
VAR IEND = range1.end< range2.end? range1.end:range2.end;
VAR newRange = ISTART< IEND?新{开始= ISTART,结束= IEND}:空;
 

这应该返回如果没有相交的时间。

Let's say i have 2 date ranges.

Those date ranges could be represented as time spans.

i want to find a date range, that falls within the two time spans.

Range 1: 2/1/2011 - 8/1/2011 (timespan of 6 months)
Range 2: 5/2/2011 - 5/28/2011 (timespan of 26 days)

so in this case, the intersection would be 5/2/2011-5/28/2011, but the ranges could move in either direction, (or not intersect at all in which case i'd want the resulting timespan to be 0 length)

in the end, i need the calendar dates of start/end of the resulting intersection time span (not just ticks/hours/days etc)

is there a elegant way to do this in c# 3.0?

UPDATE

i took StriplingWarriors code and created a method out of it..

    private static DateRange GetIntersectionRange(DateRange range1, DateRange range2) {
        var iRange = new DateRange();
        iRange.From = range1.From < range2.From ? range2.From : range1.From;
        iRange.To = range1.To < range2.To ? range1.To : range2.To;
        if (iRange.From > iRange.To) iRange = null;
        return iRange;
    }

解决方案

Something like this, perhaps?

var range1 = new{start = DateTime.Parse("2/1/2011"), end = DateTime.Parse("8/1/2011")};
var range2 = new{start = DateTime.Parse("5/2/2011"), end = DateTime.Parse("5/28/2011")};
var iStart = range1.start < range2.start ? range2.start : range1.start;
var iEnd = range1.end < range2.end ? range1.end : range2.end;
var newRange = iStart < iEnd ? new{start = iStart, end = iEnd} : null;

This should return null if there is no intersecting time period.

这篇关于在C#中时间跨度交叉点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆