Published: 02 Feb 2011
By: Scott Mitchell
Download Sample Code

5 useful and handy Helpful DateTime Extension tips

Contents [hide]


.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.


The DateTime structure's 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.


The 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.

The 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

The DateTime structure offers a number of formatting methods. There are methods that perform a specific format, such as ToShortDateString and ToLongTimeString, as well as the more general ToString. Using 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:

Unfortunately, the 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 DateTime type:

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 DateTime is null.

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.

Happy Programming!

Further Reading

<<  Previous Article Continue reading and see our next or previous articles Next Article >>

About Scott Mitchell

Scott Mitchell, author of eight ASP/ASP.NET books and founder of, 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.

Other articles in this category

Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
Exception Handling and .Net (A practical approach)
Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
jQuery Mobile ListView
In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
Book Review: SignalR: Real-time Application Development
A book review of SignalR by Simone.
JQuery Mobile Widgets Overview
An overview of widgets in jQuery Mobile.

You might also be interested in the following related blog posts

Lower Case URLs and ASP.NET MVC read more
LINQ Tip of the week: System.DateTime support read more
Looking for Rogue User Objects in Active Directory read more
You should NOT use ASP.NET MVC if. . . read more
An Extensive Examination of LINQ: The Ins and Outs of Query Operators read more
An Extensive Examination of LINQ: Extension Methods, Implicitly Typed Variables, and Object Initializers read more
Creating Extension Methods in VB read more
Fun With Named Formats, String Parsing, and Edge Cases read more
Astoria query Cheat Sheet read more
Insidious Dependencies read more


Subject Author Date
placeholder FluentDateTime project Slobodan Pavkov 2/2/2011 9:47 AM

Please login to rate or to leave a comment.