Working with Dates in C#


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.

Up Next
    Ebook Download
    View all
    Learn
    View all