I'm making a graph that cover "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.
Is this how I should use TimeSpan
, or does it overlap? 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. Look here for an example. You can then have a factory method that gives you a range for a decade: 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
:
public bool Includes(DateTime date) {
return start <= date && date <= end;
}
(assuming both start
and end
are inclusive)
Now, if you only need to deal with decades, you don't really need a full DateRange
class, just this:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With