Total votes: 0
Print: Print Article
Please login to rate or to leave a comment.
Published: 02 Feb 2011
Download Sample Code
5 useful and handy Helpful DateTime Extension tips
.NET's DateTime structure offers a variety of methods for performing actions on a date and time value. For example, the AddDays method adds a specified number of days to a
DateTime value, while the Subtract method returns a
TimeSpan object indicating the delta between two dates and times. However, there may be scenarios in which none of the built-in
DateTime methods suffice. In such cases you're stuck with writing your own logic. In the past, developers created utility classes to house such common logic. Today, this logic is commonly implemented using extension methods.
Extension methods allow a developer to "add" her own methods to an existing type without having to modify the existing type. Specifically, they are implemented as static methods using a special syntax that allows them to be called as if they were methods defined on an existing type. If you have not created extension methods in the past, consider reading Extending Base Type Functionality with Extension Methods before reading the rest of this article.
This article presents five
DateTime extension methods that I have used in various projects over the years. The complete code, unit tests, and a simple demo application are available for download. Feel free to add these extension methods to your projects.
AddDays method increments (or decrements) a date and time by a specified number of days, but what if you need to adjust a date by a specified number of weekdays? Use the
AddWeekdays extension method to add (or subtract) a specified number of weekdays.
With this extension method in place you could write code like the following, which computes the first weekday following New Year's Eve (December 31st):
After the above code executes,
firstWeekdayAfterNewYearsEve2010 equals January 3rd, 2011.
DateTime structure offers methods to add time units, but there is no method to set an existing
DateTime variable to a particular time, such as 5:00 PM. The
SetTime extension method provides this functionality, allowing a developer to assign a
DateTime variable's hour, minute, second, and/or millisecond settings.
Note that if you call
SetTime and omit the minute, second, or millisecond, these values default to a value of zero. For instance, the following code takes the current date and time (
DateTime.Now) and changes the time to 5:45:00.000 PM.
FirstDayOfMonth / LastDayOfMonth
The first or last day of the month is a common date for billing, sending reminders, and performing other recurring tasks. The following two extension methods make determining the first or last day of the month a breeze.
FirstDayOfMonth extension method simply returns the 1st of the specified date's month/year. The
LastDayOfMonth extension method uses the
DateTime structure's DaysInMonth method to determine the last day of the specified date's month/year. The following code snippet shows how you could use these two methods to determine the first and last day of the current month:
ToString for Nullable DateTime Values
DateTime structure offers a number of formatting methods. There are methods that perform a specific format, such as
ToLongTimeString, as well as the more general
ToString, you can specify a format string. .NET supplies a variety of standard and custom date and time format strings. For instance, to format a date to show the month name and day of the month, followed by a comma and the four digit year, you would use the format string
MMMM d, yyyy, as in:
ToString method – along with the other
DateTime formatting methods – do not exist for nullable types. Therefore, if to format a nullable
DateTime you need to first test to see if it has a value and then use the
Value property to get a reference to the underlying
DateTime structure, like so:
The following extension methods add
ToString functionality directly to the nullable
With these extension methods in place you can call
ToString on a nullable
DateTime as the following code snippet shows. Note that
ToString always returns an empty string when the nullable
ToRelativeDateString / ToRelativeDateStringUtc
When possible, display relative dates and times rather than absolute dates and times. Consider an online discussion board. The database records the details of each post, including the date and time it was posted. But rather than displaying the absolute date and time – such as, "February 3rd, 2011 at 4:15 PM" – consider displaying the time relative to the current date and time – such as, "Three hours ago."
Humans are used to thinking about times in relative terms. The message, "A few minutes ago" more clearly conveys when something occurred than does a long and wordy (albeit more precise) message, like "February 19th, 11:09 AM." As an added benefit, displaying dates in relative terms removes time zone nuisances - while February 19th, 11:09 AM may be the precise date and time recorded at the web server, it may be a point in the future for someone living west of the web server.
The following extension methods provide a means to generate a relative date string. The
ToRelativeDateString method generates a relative date string for a date compared to the web server's current date and time;
ToRelativeDateStringUtc generates a relative date string for a date compared to the current UTC time.
Scott Mitchell, author of eight ASP/ASP.NET books and founder of 4GuysFromRolla.com, has been working with Microsoft Web technologies since 1998. Scott works as an independent consultant, trainer, ...
This author has published 16 articles on DotNetSlackers. View other articles or the complete profile here.
You might also be interested in the following related blog posts
Lower Case URLs and ASP.NET MVC
LINQ Tip of the week: System.DateTime support
Looking for Rogue User Objects in Active Directory
You should NOT use ASP.NET MVC if. . .
An Extensive Examination of LINQ: The Ins and Outs of Query Operators
An Extensive Examination of LINQ: Extension Methods, Implicitly Typed Variables, and Object Initializers
Creating Extension Methods in VB
Fun With Named Formats, String Parsing, and Edge Cases
Astoria query Cheat Sheet
Please login to rate or to leave a comment.