简体   繁体   English

这是用TimeSpan代表几十年的最佳方式吗?

[英]Is this the best way to represent decades with TimeSpan?

I'm making a graph that cover "1930-1940", "1940-1950", "1950-1960", "1960-1970", ... 我正在制作一张涵盖"1930-1940", "1940-1950", "1950-1960", "1960-1970", ...的图表"1930-1940", "1940-1950", "1950-1960", "1960-1970", ...

I want to represent this with a DateTime and a Timespan , but I'm not really sure how to make the TimeSpan , and I find it hard to verify if my timespans are correct. 我想用DateTimeTimespan表示这个,但我不确定如何制作TimeSpan ,我发现很难验证我的时间跨度是否正确。

Is this how I should use TimeSpan , or does it overlap? 这是我应该如何使用TimeSpan ,还是重叠? If it's overlapning then how can I fix it? 如果它重叠,那么我该如何解决呢?

List<DateTime> list1 = new List<DateTime>();
List<TimeSpan> list2 = new List<TimeSpan>();

int startYearInt = 1930;

int times = 0;
const int intervalSize = 10;
for (int i = startYearInt; i < 2020; i += intervalSize)
{
    DateTime sYear = new DateTime(startYearInt + (intervalSize * times++), 1, 1);
    TimeSpan period = (sYear.AddYears(intervalSize)) - sYear;

    list1.Add(sYear);
    list2.Add(period); // <<-- Don't know if if this is correct?
}

EDIT: I have this too. 编辑:我也有这个。 And if My timespan is too small or to last it can give some problems. 如果我的时间跨度太小或持续时间可能会产生一些问题。

public bool IsInsidePeriod(DateTime dt)
{
    return dt >= FromYearDateTime && dt < FromYearDateTime.Add(periodTimeSpan);
}

You're better off creating a DateRange value type than using a DateTime and a TimeSpan like that. 创建DateRange值类型比使用DateTimeTimeSpan更好。 Look here for an example. 在这里看一个例子。 You can then have a factory method that gives you a range for a decade: DateRange.DecadeStartingOn(1930); 然后,您可以使用工厂方法为您提供十年的范围: DateRange.DecadeStartingOn(1930); . This way, you raise the level of abstraction and deal with the concepts you're referring to in the code itself . 这样,您就可以提高抽象级别并处理代码本身所引用的概念。

Your IsInsidePeriod is a simple operation for the DateRange : IsInsidePeriod是一个简单的操作的DateRange

public bool Includes(DateTime date) {
  return start <= date && date <= end;
}

(assuming both start and end are inclusive ) (假设startend包括在内

Now, if you only need to deal with decades , you don't really need a full DateRange class, just this: 现在,如果你只需要处理数十年 ,那么你真的不需要一个完整的DateRange类,就这样:

class Decade {

  public int StartYear { get; private set; }
  public int EndYear { get { return StartYear + 9; } }

  public Decade(int startYear) {
    StartYear = startYear;
  }

  public bool Includes(DateTime date) {
    return StartYear <= date.Year && date.Year <= EndYear;
  }

  public override string ToString() {
    return string.Format("{0}-{1}", StartYear, EndYear + 1);
  }

}

Or maybe a more general YearRange . 或者更普遍的YearRange

If all you are asking to do is solve your current issues then the code below works, hey I'm bored, I would however consider doing some research on DateTime ranges, comparisons (especially how the work with different TimeZones etc and intervals. 如果您要求的是解决当前的问题,那么下面的代码就可以了,嘿,我很无聊,但我会考虑对DateTime范围进行一些研究,比较(特别是如何使用不同的TimeZones等工作和间隔。

DateTime on MSDN MSDN上的DateTime

class Program
{   
    static void Main(string[] args)
    {
        int interval = 10;
        DateTime isInRangeDate = DateTime.UtcNow;

        for (int i = 1930; i < 2020; )
        {
            DateRange range = new DateRange(1, 1, i, interval);
            Console.WriteLine(string.Format("{0}: Is in range - {1}", range.ToString(), range.IsInsidePeriod(isInRangeDate)));


            i = range.EndDate.Year;
        }               

        Console.ReadLine();
    }  
}


public class DateRange
{
    public DateTime StartDate { get; private set; }
    public DateTime EndDate { get; private set; }

    public override string ToString()
    {
        return string.Format("{0}-{1}", this.StartDate.Year, this.EndDate.Year);
    }

    public DateRange(int day, int month, int year, int addYears)
    {
        StartDate = new DateTime(year, month, day, 0, 0, 0);
        EndDate = StartDate.AddYears(addYears);
    }

    public bool IsInsidePeriod(DateTime dt)
    {
        return ((dt.Date >= StartDate) && (dt.Date < EndDate));
    }
}

You can simplify your IsInPeriod method to something like this: 您可以将IsInPeriod方法简化为以下内容:

public bool IsInsidePeriod(DateTime dateToCompare, DateTime startDate, DateTime endDate)
{
    return startDate <= dateToCompare && dateToCompare < endDate;
}

As others have mentioned, TimeSpan is not buying you anything and is overcomplicating your described issue. 正如其他人所提到的, TimeSpan并没有给你买任何东西,并且使你描述的问题过于复杂。 Pay particular attention to the comparison operators. 特别注意比较运算符。 You may want either end to be exclusive rather than inclusive or vice versa. 您可能希望任何一端都是独占而不是包容,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM