Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » Visual C# » Calculating Date Difference in C#

Calculating Date Difference in C#

This article introduces the various options for calculating the date difference in C#.

Author Rank :
Page Views : 391038
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

This article introduces the various options for calculating the date difference in C#. 

  • DateTime Structure: This datatype is used to represent a time instant in C#
  • TimeSpan Structure: The TimeSpan datatype is used to represent time interval 

Calculating the Date Difference - Subtract Method

 

The DateTime.Substract method may be used in order to find the date/time difference between two instances of the DateTime method. This method does not change the value of the DateTime instance on which the method has been invoked. The result of the operation is stored in the new TimeSpan structure.

 

The TimeSpan class has a dual set of properties, one set represents the time durations in integers and another set of properties, with the names prefixed with "Total" represents the result in fractional values. The following sample code illustrates the use of the DateTime.Subtract method and the Days and TotalDays properties of the TimeSpan structure.

 

The TimeSpan structure has additional properties for the Hours, Minutes, Seconds and Milliseconds and for TotalHours, TotalMinutes, TotalSeconds and TotalMilliseconds.

 

The DateTime structure also has an overload for the Subtract method which accepts a TimeSpan and returns the DateTime value which is the result of subtracting the Timespan argument from the value of the DateTime structure on which the Subtract method has been invoked.

 

Code Sample: Calculating the Date Difference - Subtract Method.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace Console_DateTime

{

    class Program

    {

        static void Main(string[] args)

        {

            System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);

            System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);

            System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);

            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);

            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);

            Console.ReadLine();

        }

    }

}

 

Image: Results for Calculating the Date Difference - Subtract Method.

 

 

Calculating the Date Difference - Subtraction Operator

 

A more intuitive method for calculating the Date Difference is through the use of the Subtraction Operator (the minus sign). The following code sample yields the same result as the first code sample using the Subtract Method.

 

Code Sample: Calculating the Date Difference - Subtraction Operator.

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace Console_DateTime

{

    class Program

    {

        static void Main(string[] args)

        {

            System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);

            System.DateTime dtYestMidnight = new System.DateTime(2006, 9, 12, 0, 0, 0);

            System.TimeSpan diffResult = dtTodayNoon - dtYestMidnight;

            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);

            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);

            Console.ReadLine();

        }

    }

}

DateDiff Function

 

A third alternative for date subtraction in C# is by importing the Microsoft.VisualBasic namespace and invoking the DateDiff method. Opponents of this technique offer the critique that importing the namespace involves extra weight. Proponents of the technique provide contradictory arguments.

 

If the requirements are only restricted to calculating a basic date difference, the direct use of the DateTime structure is recommended.

 

Impact of TimeZones

 

The techniques described above do not take factors such as TimeZone and Daylight Savings Time into account. The operations assume that both the date arguments have been converted to the same time zone before the operation is invoked.

 

Impact of DayLight Savings Time

 

If the date calculations are performed in a locale involving Daylight Savings Time, an additional step is required to convert the DateTime object values to Universal Time by using the ToUniversalTime method.

 

  System.TimeSpan diffResult = dtTodayNoon.ToUniversalTime().Subtract(dtYestMidnight.ToUniversalTime());

 

This article is aimed at providing a quick reference for options in the framework for performing basic Date Calculations. For detailed information on DateTime manipulations, refer to Dan Roger's Coding Best Practices Using DateTime in the .NET Framework.

 

Conclusion

 

In this article, we saw the techniques and options for calculating the difference between two dates in C#. Note that the arithmetic operations do not take inherently take timezone differences into account.

Special credit goes to Carl Camera for pointing out the issues with Daylight Savings Time and the resource on .Net DateTime best practices.

 

Disclaimer

This article is for purely educational purposes and is a compilation of notes, material and my understanding on this subject. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dipal Choksi
Dipal Choksi has over 10 years of industry experience in team-effort projects and also as an individual contributor. She has been working on the .Net platform since the beta releases of .Net 1.0.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Did I miss something? by Gary On February 4, 2009
In the sample code below, the variable "dtYestMidnight" is not declared. Only dtTodayMidnight is declared. Is this a typo? using System; using System.Collections.Generic; using System.Text; namespace Console_DateTime { class Program { static void Main(string[] args) { System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0); System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0); System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight); Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days); Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays); Console.ReadLine(); } } }
Reply | Email | Modify 
System.Data.Linq.SqlClient.SqlMethods DateDiff methods by sheir On January 7, 2010

What about using the System.Data.Linq namespace and its SqlMethods.DateDiffMonth method?

For example, say...

DateTime starDT = {01-Jul-2009 12:00:00 AM}

DateTime endDT = {01-Nov-2009 12:00:00 AM}

then

int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(startDT, endDT);

==> 4

There are other DateDiff static methods in the SqlMethods class.

Reply | Email | Modify 
Date validation according to particular date in c#-please by muralekarthick On January 18, 2010
Hi there

         I would be happy if you could help me , in getting the date validated according to particular date given by user, for instance: discharge date should not be before than admit date given by user
Reply | Email | Modify 
Difference between dates by Pavani On November 19, 2010
How to get difference between dates in Years, months and days
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.