ResourceManagement
ResourceManagement copied to clipboard
DateTime type extension methods
It would be great to have some extension methods on the DateTime object to assist with the regular date calculations performed in this application
As an example, it might be useful to have a couple of extension methods which compare a certain DateTime against a Date (range), e.g. does "Wed July 17th, 8:09pm" fall on "Wed Jul 17th"?
var dateTime = new DateTime(2019, 07, 17, 20, 09, 00);
var date = new DateTime(2019, 07, 17);
bool check = dateTime.IsOn(date);
Internally, the IsOn extension method would be coded as (pseudo code):
return dateTime >= date and dateTime < date + 1 day;
Similarly, additional extension methods can be defined:
IsOnOrAfter(pseudo:dateTime >= date)IsAfter(pseudo:dateTime >= date + 1 day)IsBeforeOrOn(pseudo:dateTime < date + 1 day)IsBefore(pseudo:dateTime < date)IsBetween(pseudo:dateTime >= date1 and dateTime < date2 + 1 day)
The benefit of using these extension methods is that it makes it very clear what the developer's intention was (and hopefully prevent fence post errors).
Hi I have added the extension methods for comparing a DateTime object's date with another DateTime object's date (these are the methods above except each method has been appended with 'Date' - IsOnDate, IsBeforeDate etc), aswell as extension methods for comparing entire DateTime objects with other DateTime objects (these are named like IsSameOrBefore, IsSameOrAfter and will take into account the time property of the objects). Should I implement the extension methods in the ScheduleManager? For example:
if (!(ts1.StartDateTime <= ts2.EndDateTime && ts2.StartDateTime <= ts1.EndDateTime)) {
logger.LogTrace("Did not find an intersection");
return null;
}
will become:
if (!(ts1.StartDateTime.IsSameOrBefore(ts2.EndDateTime)
&& ts2.StartDateTime.IsSameOrBefore(ts1.EndDateTime))) {
logger.LogTrace("Did not find an intersection");
return null;
}
@marblekirby Amazingly quick turn-around 👍
The reason for me not including extension methods for comparing DateTime against DateTime is that they don't add value to just using var earlier = dateTime1 < dateTime2. In my mind the latter is clearer for the next developer reading the code.
So I think your initial commit 6be1a6bed4e1362b26b1e312105bc43bb3509501 is the right way to go, but it is up to @csharpfritz what he prefers.
Sure, I agree with you @ultramark, I think you are right and we should maybe go back to that commit.
I'm ok adding the extension methods, but I think the more valuable feedback here is that we should create some methods for comparing schedule or timeslot objects