Another quick post with some useful extension methods for the
System.DateTime struct. I’ve been working a lot with the DateTime type over the past couple of weeks. One particular use case has been to pass a “start” and an “end” DateTime to some SQL Server stored procedure. The stored procedure then returns some data based on some timestamp field that falls between the start and end DateTime’s passed in.
In the code I was maintaining, the previous developer had created a DateTime value using DateTime.Now, which returns a DateTime with the time part also populated to the current system time. So when passing this DateTime to the stored proc as a “start” DateTime, the proc was looking from the time-part onwards on the specific day represented by the DateTime. Likewise, when using a similarly created DateTime for the “end” DateTime, the stored proc only returned rows upto the time-part. This was undesired behaviour because the original intention was to retrieve all of the records between two specified days (inclusive of the start and end days).
I decided to tackle this at the application-level. This was mainly to keep the stored procedure flexible so that it can continue to handle retrieval of records at the more granular time level if required. I decided to implement this functionality by adding two extension methods on DateTime, namely, ResetTimeToStartOfDay and ResetTimeToEndOfDay. These return new DateTime values with the time part appropriately set. The idea is to call ResetTimeToStartOfDay on the “start” DateTime and ensure that the returned DateTime is sent to the stored procedure. Likewise, call ResetTimeToEndOfDay on the “end” DateTime. I’ve included the implementation of the two methods below – very simple but useful to have in your library.
- public static DateTime ResetTimeToStartOfDay(this DateTime dateTime) {
- return new DateTime(
- dateTime.Year,
- dateTime.Month,
- dateTime.Day,
- 0, 0, 0, 0);
- }
- public static DateTime ResetTimeToEndOfDay(this DateTime dateTime) {
- return new DateTime(
- dateTime.Year,
- dateTime.Month,
- dateTime.Day,
- 23, 59, 59, 999);
- }
Here is a detailed tutorial:
DateTime in C#