Last active
August 29, 2015 14:26
-
-
Save christopherbauer/778df106b03107fbfc32 to your computer and use it in GitHub Desktop.
Blog - Date Range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public struct DateRange | |
| { | |
| private readonly DateTime _start; | |
| private readonly DateTime _end; | |
| public DateRange(DateTime start, DateTime end) | |
| : this() | |
| { | |
| if (start > end) | |
| { | |
| throw new ArgumentException("Start date time cannot be after end date time"); | |
| } | |
| _start = start; | |
| _end = end; | |
| } | |
| public DateTime Start | |
| { | |
| get { return _start.Date; } | |
| } | |
| public DateTime End | |
| { | |
| get { return _end.Date; } | |
| } | |
| public static DateRange FromDays(DateTime start, int days) | |
| { | |
| if (days < 0) | |
| { | |
| return new DateRange(start.AddDays(days), start); | |
| } | |
| return new DateRange(start, start.AddDays(days)); | |
| } | |
| public bool InRange(DateTime dateTime) | |
| { | |
| var date = dateTime.Date; | |
| return date.Date >= Start.Date && date <= End; | |
| } | |
| public static bool operator ==(DateRange range1, DateRange range2) | |
| { | |
| return range1.Start == range2.Start && range1.End == range2.End; | |
| } | |
| public static bool operator !=(DateRange range1, DateRange range2) | |
| { | |
| return !(range1 == range2); | |
| } | |
| public bool Equals(DateRange other) | |
| { | |
| return _start.Date.Equals(other._start.Date) && _end.Date.Equals(other._end.Date); | |
| } | |
| public override bool Equals(object obj) | |
| { | |
| if (ReferenceEquals(null, obj)) return false; | |
| return obj is DateRange && Equals((DateRange)obj); | |
| } | |
| public override int GetHashCode() | |
| { | |
| unchecked | |
| { | |
| return (_start.Date.GetHashCode() * 397) ^ _end.Date.GetHashCode(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment