Working With C# DateTime

C# DateTime object is used to work with dates and times in .NET. In this article, I cover the following DateTime topics with C# code examples,
  1. How to create a DateTime
  2. Understand DateTime properties
  3. How to add and subtract date and time using DateTime
  4. Find days in a month and year
  5. How to compare two dates, times or DateTime
  6. How to format dates and times

1. How to create a DateTime in C#

There are several ways to create a DateTime object. A DateTime object can have a Date, Time, Localization, culture, milliseconds, and kind. The value of DateTime is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D. 

The code in Listing 1 uses various constructors of DateTime structure to create DateTime objects.

// Create a DateTime from date and time  
DateTime dob = new DateTime(1974, 7, 10, 7, 10, 24);  
   
// Create a DateTime from a String  
string dateString = "7/10/1974 7:10:24 AM";  
DateTime dateFromString =  
    DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture);  
Console.WriteLine(dateFromString.ToString());  
   
// Empty DateTime  
DateTime emptyDateTime = new DateTime();  
   
// Just date  
DateTime justDate = new DateTime(2002, 10, 18);  
   
// DateTime from Ticks  
DateTime justTime = new DateTime(1000000);  
   
// DateTime with localization  
DateTime dateTimeWithKind = new DateTime(1974, 7, 10, 7, 10, 24, DateTimeKind.Local);  
   
// DateTime with date, time and milliseconds  
DateTime dateTimeWithMilliseconds = new DateTime(2010, 12, 15, 5, 30, 45, 100);  

Listing 1

2. C# DateTime Properties

The Date and the Time properties of DateTime get the date and the time of a DateTime. Some self-explanatory DateTime properties are Hour, Minute, Second, Millisecond, Year, Month, and Day. 

Here is a list of some other properties with their brief description.

  • DayOfWeek property returns the name of the day in a week.
  • DayOfYear property returns the day of a year.
  • TimeOfDay property returns the time element in a DateTime.
  • Today property returns the DateTime object that has today's values. Time value is 12:00:00.
  • Now property returns a DateTime object that has right now date and time values.
  • UtcNow property returns a DateTime in Coordinated Universal Time (UTC)
  • A tick represents one hundred nanoseconds or one ten-millionth of a second. Ticks property of DateTime returns the number of ticks in a DateTime.
  • Kind property returns a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. The default value is unspecified.

The code listed in Listing 2 creates a DateTime object and reads its properties. 

DateTime dob = new DateTime(1974, 7, 10, 7, 10, 24);  
Console.WriteLine("Day:{0}", dob.Day);  
Console.WriteLine("Month:{0}", dob.Month);  
Console.WriteLine("Year:{0}", dob.Year);  
Console.WriteLine("Hour:{0}", dob.Hour);  
Console.WriteLine("Minute:{0}", dob.Minute);  
Console.WriteLine("Second:{0}", dob.Second);  
Console.WriteLine("Millisecond:{0}", dob.Millisecond);  
Console.WriteLine("Day of Week:{0}", dob.DayOfWeek);  
Console.WriteLine("Day of Year: {0}", dob.DayOfYear);  
Console.WriteLine("Time of Day:{0}", dob.TimeOfDay);  
Console.WriteLine("Tick:{0}", dob.Ticks);  
Console.WriteLine("Kind:{0}", dob.Kind);  

 Listing 2

The output of Listing 2 looks like Figure 1.

DateTimeImg1.gif
Figure 1

3. Adding and Subtracting DateTime in C#

DateTime structure provides methods to add and subtract date and time to and from a DateTime object. The TimeSpan structure plays a major role in addition and subtraction.

We can use Add and Subtract methods to add and subtract date and time from a DateTime object. First we create a TimeSpan with a date and/or time values and use Add and Subtract methods.

The code listed in Listing 3 adds and subtracts 30 days from today and displays the day on the console. 

DateTime aDay = DateTime.Now;  
TimeSpan aMonth = new System.TimeSpan(30, 0, 0, 0);  
DateTime aDayAfterAMonth = aDay.Add(aMonth);  
DateTime aDayBeforeAMonth = aDay.Subtract(aMonth);  
Console.WriteLine("{0:dddd}", aDayAfterAMonth);  
Console.WriteLine("{0:dddd}", aDayBeforeAMonth);  

Listing 3 

The DateTime structure has methods to add years, days, hours, minutes, seconds, milliseconds and ticks. The code listed in Listing 4 uses these Addxxx methods to add various components to a DateTime object.

// Add Years and Days  
aDay.AddYears(2);            
aDay.AddDays(12);  
// Add Hours, Minutes, Seconds, Milliseconds, and Ticks  
aDay.AddHours(4.25);  
aDay.AddMinutes(15);  
aDay.AddSeconds(45);             
aDay.AddMilliseconds(200);  
aDay.AddTicks(5000);   

Listing 4

The DateTime structure does not have similar Subtract methods. Only Subtract method is used to subtract the DateTime components. For example, if we need to subtract 12 days from a DateTime, we can create another DateTime object or a TimeSpan object with 12 days and subtract it from the DateTime. Alternatively, we can use a minus operator to subtract a DateTime or TimeSpan from a DateTime.

The code snippet in Listing 5 creates a DateTime object and subtracts another DateTime and a TimeSpan object. Code also shows how to subtract just days or hours or other components from a DateTime. 

DateTime dob = new DateTime(2000, 10, 20, 12, 15, 45);  
DateTime subDate = new DateTime(2000, 2, 6, 13, 5, 15);  
   
// TimeSpan with 10 days, 2 hrs, 30 mins, 45 seconds, and 100 milliseconds  
TimeSpan ts = new TimeSpan(10, 2, 30, 45, 100);  
   
// Subtract a DateTime  
TimeSpan diff1 = dob.Subtract(subDate);  
Console.WriteLine(diff1.ToString());  
   
// Subtract a TimeSpan  
DateTime diff2 = dob.Subtract(ts);  
Console.WriteLine(diff2.ToString());  
   
// Subtract 10 Days  
DateTime daysSubtracted = new DateTime(dob.Year, dob.Month, dob.Day - 10);  
Console.WriteLine(daysSubtracted.ToString());  
   
// Subtract hours, minutes, and seconds  
DateTime hms = new DateTime(dob.Year, dob.Month, dob.Day, dob.Hour - 1, dob.Minute - 15, dob.Second - 15);  
Console.WriteLine(hms.ToString());  

 Listing 5

4. Find Days in a Month

The DaysInMonth static method returns the number of days in a month. This method takes a year and a month in numbers from 1 to 12. The code snippet in Listing 6 gets the number of days in Feb month of year 2002. The output is 28 days.

int days = DateTime.DaysInMonth(2002, 2);  
Console.WriteLine(days);  

Listing 6

Using the same approach, we can find out total number of days in a year. The GetDaysInAYear method in Listing 7 takes a year and returns total number of days in that year.

private int GetDaysInAYear(int year) {
    int days = 0;
    for (int i = 1; i <= 12; i++) {
        days += DateTime.DaysInMonth(year, i);
    }
    return days;
}

 Listing 7

5. Compare Two DateTime In C#

The Compare static method is used to compare two DateTime objects. If result is 0, both objects are the same. If the result is less than 0, then the first DateTime is earlier; otherwise the first DateTime is later.

The code snippet in Listing 8 compares two DateTime objects.

DateTime firstDate = new DateTime(2002, 10, 22);  
DateTime secondDate = new DateTime(2009, 8, 11);  
int result = DateTime.Compare(firstDate, secondDate);  
   
if (result < 0)  
    Console.WriteLine("First date is earlier");  
else if (result == 0)  
    Console.WriteLine("Both dates are same");  
else  
    Console.WriteLine("First date is later");  

Listing 8

The CompareTo method can also be used to compare two dates. This method takes a DateTime or object. The code snippet in Listing 9 compares two DateTime objects using the CompareTo method. 

DateTime firstDate = new DateTime(2002, 10, 22);  
DateTime secondDate = new DateTime(2009, 8, 11);  
int compareResult = firstDate.CompareTo(secondDate);  
if (compareResult < 0)  
    Console.WriteLine("First date is earlier");  
else if (compareResult == 0)  
    Console.WriteLine("Both dates are same");  
else  
    Console.WriteLine("First date is later");  

Listing 9

6. Format C# DateTime

I have to admit; the folks at Microsoft have done a great job of providing DateTime formatting solutions. Now you can format a DateTime to any kind of string format you can imagine.

The GetDateTimeFormats method returns all possible DateTime formats for the current culture of a computer. The code snippet in Listing 10 returns an array of strings of all possible standard formats.

DateTime dob = new DateTime(2002, 10, 22);  
string[] dateFormats = dob.GetDateTimeFormats();  
foreach (string format in dateFormats)  
    Console.WriteLine(format)  

Listing 10

The code snippet in Listing 10 generates output as in Figure 2.

DateTimeImg2.gif
Figure 2

The GetDateTimeFormats method also has an overload that takes a format specifier as a parameter and converts a DateTime to that format. It is very important to understand the DateTime format specifiers to get the desired formats. Table 1 summarizes the formats and their codes.

Code Pattern Format Sample
"d" Sort date    
"D" Long date    
"f" Full date time. Short time.    
"F" Full date time. Long time.    
"g" Generate date time. Short time.    
"G" General date time. Long time.    
"M", 'm" Month/day.    
"O", "o" Round-trip date/time.    
"R", "r" RFC1123    
"s" Sortable date time.    
"t" Sort time.    
"T" Long time.    
"u" Universal sortable date time.    
"U" Universal full date time.    
"Y", "y" Year month.    

Table 1

The code snippet in Listing 11 uses some of the DateTime format specifiers.

DateTime dob = new DateTime(2002, 10, 22);  
// DateTime Formats: d, D, f, F, g, G, m, o, r, s, t, T, u, U,  
Console.WriteLine("----------------");  
Console.WriteLine("d Formats");  
Console.WriteLine("----------------");  
string[] dateFormats = dob.GetDateTimeFormats('d');  
foreach (string format in dateFormats)  
    Console.WriteLine(format);  
Console.WriteLine("----------------");  
Console.WriteLine("D Formats");  
Console.WriteLine("----------------");  
dateFormats = dob.GetDateTimeFormats('D');  
foreach (string format in dateFormats)  
    Console.WriteLine(format);  
   
Console.WriteLine("----------------");  
Console.WriteLine("f Formats");  
Console.WriteLine("----------------");  
dateFormats = dob.GetDateTimeFormats('f');  
foreach (string format in dateFormats)  
    Console.WriteLine(format);  
   
Console.WriteLine("----------------");  
Console.WriteLine("F Formats");  
Console.WriteLine("----------------");  
dateFormats = dob.GetDateTimeFormats('F');  
foreach (string format in dateFormats)  
    Console.WriteLine(format);  

Listing 11

The code snippet in Listing 11 generates output as in Figure 3

DateTimeImg3.gif
Figure 3

We can also format a DateTime by passing the format specifier in the ToString() method of DateTime. The code snippet in Listing 12 formats a DateTime using ToString() method.

Console.WriteLine(dob.ToString("r"));

Listing 12

The code snippet in Listing 13 uses some of the DateTime format specifiers within the ToString() method to format a DateTime. 

DateTime dob = new DateTime(2002, 10, 22);  
Console.WriteLine("d: "+ dob.ToString("d"));  
Console.WriteLine("D: "+ dob.ToString("D"));  
Console.WriteLine("f: "+ dob.ToString("f"));  
Console.WriteLine("F: "+ dob.ToString("F"));  
Console.WriteLine("g: " + dob.ToString("g"));  
Console.WriteLine("G: " + dob.ToString("G"));  
Console.WriteLine("m: " + dob.ToString("m"));  
Console.WriteLine("M: " + dob.ToString("M"));  
Console.WriteLine("o: " + dob.ToString("o"));  
Console.WriteLine("O: " + dob.ToString("O"));  
Console.WriteLine("r: " + dob.ToString("r"));  
Console.WriteLine("R: " + dob.ToString("R"));  
Console.WriteLine("s: " + dob.ToString("s"));  
Console.WriteLine("t: " + dob.ToString("t"));  
Console.WriteLine("T: " + dob.ToString("T"));  
Console.WriteLine("u: " + dob.ToString("u"));  
Console.WriteLine("U: " + dob.ToString("U"));  
Console.WriteLine("y: " + dob.ToString("y"));  
Console.WriteLine("Y: " + dob.ToString("Y"));  

 Listing 13 

The code snippet in Listing 13 generates output as in Figure 4. 

DateTimeImg4.gif
Figure 4

Here is a detailed DateTime Formats in C#

7. Get Leap Year and Daylight Saving Time

The IsDayLightSavingTime() and IsLeapYear() methods can be used to determine if a DateTime is DayLightSaving time and leap year respectively. The code snippet in Listing 14 shows how to use these methods. 

DateTime dob = new DateTime(2002, 10, 22);  
Console.WriteLine(dob.IsDaylightSavingTime());  
Console.WriteLine(DateTime.IsLeapYear(dob.Year));  

 Listing 14

8. How to convert a string to DateTime

The Parse method is used to convert a string to a DateTime object. The string passed on the Parse method must have a correct DateTime format. Conversion from a DateTime to a string is done using the ToString() method.

The code snippet in Listing 15 converts a string to a DateTime.

string dt = "2010-10-04T20:12:45-5:00";  
DateTime newDt = DateTime.Parse(dt);  
Console.WriteLine(newDt.ToString());  

 Listing 15

9. How to convert C# DateTime

The DateTime structure is full of self-explanatory conversion methods that convert a DateTime to a specified type. These methods are ToBinary, ToFileTime, ToLocalTime, ToLongDateString, ToLongTimeString, ToOADate, ToShortDateString, ToShortTimeString, ToString, and ToUniversalTime.

The code snippet in Listing 16 uses some of these methods to convert a DateTime to specified types.

DateTime dob = new DateTime(2002, 10, 22);  
Console.WriteLine("ToString: " + dob.ToString());  
Console.WriteLine("ToBinary: " + dob.ToBinary());  
Console.WriteLine("ToFileTime: " + dob.ToFileTime());  
Console.WriteLine("ToLocalTime: " + dob.ToLocalTime());  
Console.WriteLine("ToLongDateString: " + dob.ToLongDateString());  
Console.WriteLine("ToLongTimeString: " + dob.ToLongTimeString());  
Console.WriteLine("ToOADate: " + dob.ToOADate());  
Console.WriteLine("ToShortDateString: " + dob.ToShortDateString());  
Console.WriteLine("ToShortTimeString: " + dob.ToShortTimeString());  
Console.WriteLine("ToUniversalTime: " + dob.ToUniversalTime());  

 Listing 16

The code snippet in Listing 11 generates output looks like Figure 5.

DateTimeImg5.gif
Figure 5

10. C# TimeZone Sample

Here is code sample on TimeZone (source MSDN)

// Example of selected TimeZone class elements.   
using System;
using System.Globalization;
class TimeZoneDemo {
    static void Main() {
        const string dataFmt = "{0,-30}{1}";
        const string timeFmt = "{0,-30}{1:yyyy-MM-dd HH:mm}";
        Console.WriteLine("This example of selected TimeZone class " + "elements generates the following \n" + "output, which varies depending on the " + "time zone in which it is run.\n");
        // Get the local time zone and the current local time and year.  
        TimeZone localZone = TimeZone.CurrentTimeZone;
        DateTime currentDate = DateTime.Now;
        int currentYear = currentDate.Year;
        // Display the names for standard time and daylight saving    
        // time for the local time zone.  
        Console.WriteLine(dataFmt, "Standard time name:", localZone.StandardName);
        Console.WriteLine(dataFmt, "Daylight saving time name:", localZone.DaylightName);
        // Display the current date and time and show if they occur    
        // in daylight saving time.  
        Console.WriteLine("\n" + timeFmt, "Current date and time:", currentDate);
        Console.WriteLine(dataFmt, "Daylight saving time?", localZone.IsDaylightSavingTime(currentDate));
        // Get the current Coordinated Universal Time (UTC) and UTC    
        // offset.  
        DateTime currentUTC = localZone.ToUniversalTime(currentDate);
        TimeSpan currentOffset = localZone.GetUtcOffset(currentDate);
        Console.WriteLine(timeFmt, "Coordinated Universal Time:", currentUTC);
        Console.WriteLine(dataFmt, "UTC offset:", currentOffset);
        // Get the DaylightTime object for the current year.  
        DaylightTime daylight = localZone.GetDaylightChanges(currentYear);
        // Display the daylight saving time range for the current year.  
        Console.WriteLine("\nDaylight saving time for year {0}:", currentYear);
        Console.WriteLine("{0:yyyy-MM-dd HH:mm} to " + "{1:yyyy-MM-dd HH:mm}, delta: {2}", daylight.Start, daylight.End, daylight.Delta);
    }
}

Summary

C# DateTime structure is used to represent and work with dates and time in .NET. In this chapter, I demonstrated how to create a DateTime object and use it in your application. I also discussed various properties of the DateTime and how to add and subtract dates and times. After that I discussed how to compare, format, and convert dates and times. 

Further Readings

Here are some more articles on DateTime you may want to check out,


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.