You will have to write your own class to manage this.
Let's assume that your date strings are always in one of the following formats:
- yyyy-M-d HH:mm:ss
- yyyy-M-d HH:mm
- yyyy-M-d HH
- yyyy-M-d
- yyyy-M
- yyyy
Then you can write a class to encapsulate this as follows:
public sealed class TimeRange
{
public TimeRange(string dateTimeString)
{
DateTime dateTime;
if (DateTime.TryParseExact(dateTimeString, @"yyyy-M-d HH\:mm\:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddSeconds(1);
}
else if (DateTime.TryParseExact(dateTimeString, @"yyyy-M-d HH\:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddMinutes(1);
}
else if (DateTime.TryParseExact(dateTimeString, @"yyyy-M-d HH", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddHours(1);
}
else if (DateTime.TryParseExact(dateTimeString, @"yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddDays(1);
}
else if (DateTime.TryParseExact(dateTimeString, @"yyyy-M", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddMonths(1);
}
else if (DateTime.TryParseExact(dateTimeString, @"yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddYears(1);
}
else
{
throw new ArgumentException("date/time is invalid: " + dateTimeString, "dateTimeString");
}
}
public DateTime Start
{
get
{
return _start;
}
}
public DateTime ExclusiveEnd
{
get
{
return _end;
}
}
private readonly DateTime _start;
private readonly DateTime _end;
}
Note that for simplicity the end of the range, ExclusiveEnd
, is expressed as an exclusive range. That means you'd make comparisons like:
if (timeRange.Start <= targetDateTime && targetDateTime < timeRange.ExclusiveEnd)
...
rather than the following, which would be incorrect:
if (timeRange.Start <= targetDateTime && targetDateTime <= timeRange.ExclusiveEnd)
...
Note the difference between < timeRange.ExclusiveEnd
and <= timeRange.ExclusiveEnd
To avoid this subtlety you could add to the class a Contains(DateTime)
method like:
public bool Contains(DateTime target)
{
return (_start <= target) && (target < _end);
}