SIGN UP MEMBER LOGIN:    
ARTICLE

Working with Dates in C#

Posted by Mamta M Articles | Visual C# September 20, 2011
In this article we will discuss various handy date and time utilities that can come in use for day to day tasks.
Reader Level:

Often in C#, we need to work with date and time values, format them or manipulate them in some way. The DateTime structure in C# provides a number of methods and properties that are useful to manipulate dates.

The following are some handy little examples which make use of some of these methods and properties and can help in day to day date-related operations.

Adding days to an existing date:

DateTime date1;

// Get the value of date1, for example, here it is hard-coded

date1 = Convert.ToDateTime("10/01/2011");

// Calculate new date

DateTime newdate= firstdate.AddDays(20);

// Now, print the newdate or use it in any way you want

Setting date format to the form 31/05/2010

DateTime date1;

// Get the value of date1, for example, here it is hard-coded

 Date1 = DateTime.Today;

string strDate  = d.ToString("d/MM/yyyy");

// Now, print the strDate string or use it in any way you want

Getting difference between two dates

The Compare method of DateTime structure is great for comparing date values.
The following example shows an example of determining if date applicable for discount has expired.

using System;
using System.ComponentModel;

public class TestForDiscount

{

public static void Main()

{

DateTime validFrom,validTo;

Console.WriteLine("Enter from date for discount");

validFrom = Convert.ToDateTime(Console.ReadLine());

Console.WriteLine("Enter to date for discount");

validTo = Convert.ToDateTime(Console.ReadLine());

if (DateTime.Compare(validFrom,DateTime.Today) <0 && DateTime.Compare(DateTime.Today, validTo)<0)

{              

Console.WriteLine("Discount is applicable");

}

else

{

Console.WriteLine("Discount has expired");

}

}

}

The following example shows determining difference between two dates.

using System;
using System.ComponentModel;

public class TestForDiscount

{

public static void Main()

{

            DateTime validFrom, validTo;
            Console.WriteLine("Enter from date for discount");
            validFrom = Convert.ToDateTime(Console.ReadLine());
            Console.WriteLine("Enter to date for discount");
            validTo = Convert.ToDateTime(Console.ReadLine());
            TimeSpan diff;
            if (DateTime.Compare(validFrom, DateTime.Today) < 0 &&
              DateTime.Compare(DateTime.Today, validTo) < 0)
           {
                diff = validFrom - validTo;
                Console.WriteLine(                
                   validFrom.Subtract(validTo.Date).Days); 
           }
            else
           {
               diff = validTo-validFrom;
               Console.WriteLine(
                 validTo.Subtract(validFrom.Date).Days);
           }
     }
}

Getting a 24 hour time

Actually, there is no 24:00:00 at all because 24 hour time goes from 0:00:00 to 23:59:59. It does not progress beyond 23:59:59. So to get the 24 hour time, what you will use is
var time = TimeSpan.Parse("23:59:59");

Apart from these utilities, you may also need to format date and time strings depending on your requirements. An excellent resource regarding custom date and time format strings is available at the following link:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

A useful structure related to date and time is the TimeSpan structure. Check here for details:

http://msdn.microsoft.com/en-us/library/system.timespan%28v=VS.100%29.aspx

Summary: This article discusses various handy date and time utilities that can come in use for day to day tasks.

Login to add your contents and source code to this article
share this article :
post comment
 

Hi khushi, for that you will have to write a SQL query to extract the dates. That is beyond the scope of this article, you can refer other articles on this site for that.

Posted by Mamta M Dec 08, 2011

suppose we are maintaining a library database..and if we wish to see books issued of a particular date...den how to do it in visual studio?

Posted by khushi k Dec 07, 2011

This must be a blog not an article...

Posted by Suthish Nair Sep 21, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    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.
Team Foundation Server Hosting
Become a Sponsor