Working with DateTime in C#

In .NET Framework, a DateTime structure represents dates and times. The value of DateTime is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.

This chapter is all about date and time representation in .NET framework.

The chapter covers the following topics:

  • How to create a DateTime
  • Understand DateTime properties
  • How to add and subtract date and time using DateTime
  • Find days in a month and year
  • How to compare two dates, times or DateTime
  • How to format dates and times

Creating DateTime

There are several ways to create a DateTime object. A DateTime object can have a Date, Time, Localization, culture, milliseconds, and kind.

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

  1. // Create a DateTime from date and time  
  2. DateTime dob = new DateTime(1974, 7, 10, 7, 10, 24);  
  3.    
  4. // Create a DateTime from a String  
  5. string dateString = "7/10/1974 7:10:24 AM";  
  6. DateTime dateFromString =  
  7.     DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture);  
  8. Console.WriteLine(dateFromString.ToString());  
  9.    
  10. // Empty DateTime  
  11. DateTime emptyDateTime = new DateTime();  
  12.    
  13. // Just date  
  14. DateTime justDate = new DateTime(2002, 10, 18);  
  15.    
  16. // DateTime from Ticks  
  17. DateTime justTime = new DateTime(1000000);  
  18.    
  19. // DateTime with localization  
  20. DateTime dateTimeWithKind = new DateTime(1974, 7, 10, 7, 10, 24, DateTimeKind.Local);  
  21.    
  22. // DateTime with date, time and milliseconds  
  23. DateTime dateTimeWithMilliseconds = new DateTime(2010, 12, 15, 5, 30, 45, 100);  
  24.    

 Listing 1

 

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. 

  1. DateTime dob = new DateTime(1974, 7, 10, 7, 10, 24);  
  2. Console.WriteLine("Day:{0}", dob.Day);  
  3. Console.WriteLine("Month:{0}", dob.Month);  
  4. Console.WriteLine("Year:{0}", dob.Year);  
  5. Console.WriteLine("Hour:{0}", dob.Hour);  
  6. Console.WriteLine("Minute:{0}", dob.Minute);  
  7. Console.WriteLine("Second:{0}", dob.Second);  
  8. Console.WriteLine("Millisecond:{0}", dob.Millisecond);  
  9.    
  10. Console.WriteLine("Day of Week:{0}", dob.DayOfWeek);  
  11. Console.WriteLine("Day of Year: {0}", dob.DayOfYear);  
  12. Console.WriteLine("Time of Day:{0}", dob.TimeOfDay);  
  13. Console.WriteLine("Tick:{0}", dob.Ticks);  
  14. Console.WriteLine("Kind:{0}", dob.Kind);  

 Listing 2

 

The output of Listing 2 looks like Figure 1.

 

DateTimeImg1.gif
Figure 1

 

Adding and Subtracting DateTime

 

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. 

  1. DateTime aDay = DateTime.Now;  
  2. TimeSpan aMonth = new System.TimeSpan(30, 0, 0, 0);  
  3. DateTime aDayAfterAMonth = aDay.Add(aMonth);  
  4. DateTime aDayBeforeAMonth = aDay.Subtract(aMonth);  
  5. Console.WriteLine("{0:dddd}", aDayAfterAMonth);  
  6. Console.WriteLine("{0:dddd}", aDayBeforeAMonth);  
  7.    

 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. 

  1. // Add Years and Days  
  2. aDay.AddYears(2);            
  3. aDay.AddDays(12);  
  4. // Add Hours, Minutes, Seconds, Milliseconds, and Ticks  
  5. aDay.AddHours(4.25);  
  6. aDay.AddMinutes(15);  
  7. aDay.AddSeconds(45);             
  8. aDay.AddMilliseconds(200);  
  9. 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. 

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

 Listing 5

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.

  1. int days = DateTime.DaysInMonth(2002, 2);  
  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. 

  1. private int GetDaysInAYear(int year)  
  2. {  
  3.     int days = 0;  
  4.     for (int i = 1; i <= 12; i++)  
  5.     {  
  6.         days += DateTime.DaysInMonth(year, i);  
  7.     }  
  8.     return days;  
  9. }  
  10.    

 Listing 7

Compare Two DateTime

 

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.

  1. DateTime firstDate = new DateTime(2002, 10, 22);  
  2. DateTime secondDate = new DateTime(2009, 8, 11);  
  3. int result = DateTime.Compare(firstDate, secondDate);  
  4.    
  5. if (result < 0)  
  6.     Console.WriteLine("First date is earlier");  
  7. else if (result == 0)  
  8.     Console.WriteLine("Both dates are same");  
  9. else  
  10.     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. 

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

 Listing 9

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

  1. DateTime dob = new DateTime(2002, 10, 22);  
  2. string[] dateFormats = dob.GetDateTimeFormats();  
  3. foreach (string format in dateFormats)  
  4.     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.

  1. DateTime dob = new DateTime(2002, 10, 22);  
  2. // DateTime Formats: d, D, f, F, g, G, m, o, r, s, t, T, u, U,  
  3. Console.WriteLine("----------------");  
  4. Console.WriteLine("d Formats");  
  5. Console.WriteLine("----------------");  
  6. string[] dateFormats = dob.GetDateTimeFormats('d');  
  7. foreach (string format in dateFormats)  
  8.     Console.WriteLine(format);  
  9. Console.WriteLine("----------------");  
  10. Console.WriteLine("D Formats");  
  11. Console.WriteLine("----------------");  
  12. dateFormats = dob.GetDateTimeFormats('D');  
  13. foreach (string format in dateFormats)  
  14.     Console.WriteLine(format);  
  15.    
  16. Console.WriteLine("----------------");  
  17. Console.WriteLine("f Formats");  
  18. Console.WriteLine("----------------");  
  19. dateFormats = dob.GetDateTimeFormats('f');  
  20. foreach (string format in dateFormats)  
  21.     Console.WriteLine(format);  
  22.    
  23. Console.WriteLine("----------------");  
  24. Console.WriteLine("F Formats");  
  25. Console.WriteLine("----------------");  
  26. dateFormats = dob.GetDateTimeFormats('F');  
  27. foreach (string format in dateFormats)  
  28.     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. 

  1. DateTime dob = new DateTime(2002, 10, 22);  
  2. Console.WriteLine("d: "+ dob.ToString("d"));  
  3. Console.WriteLine("D: "+ dob.ToString("D"));  
  4. Console.WriteLine("f: "+ dob.ToString("f"));  
  5. Console.WriteLine("F: "+ dob.ToString("F"));  
  6. Console.WriteLine("g: " + dob.ToString("g"));  
  7. Console.WriteLine("G: " + dob.ToString("G"));  
  8. Console.WriteLine("m: " + dob.ToString("m"));  
  9. Console.WriteLine("M: " + dob.ToString("M"));  
  10. Console.WriteLine("o: " + dob.ToString("o"));  
  11. Console.WriteLine("O: " + dob.ToString("O"));  
  12. Console.WriteLine("r: " + dob.ToString("r"));  
  13. Console.WriteLine("R: " + dob.ToString("R"));  
  14. Console.WriteLine("s: " + dob.ToString("s"));  
  15. Console.WriteLine("t: " + dob.ToString("t"));  
  16. Console.WriteLine("T: " + dob.ToString("T"));  
  17. Console.WriteLine("u: " + dob.ToString("u"));  
  18. Console.WriteLine("U: " + dob.ToString("U"));  
  19. Console.WriteLine("y: " + dob.ToString("y"));  
  20. Console.WriteLine("Y: " + dob.ToString("Y"));  
  21.    

 Listing 13

 

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

 

DateTimeImg4.gif
Figure 4    

 

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. 

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

 Listing 14

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

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

 Listing 15

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

  1. DateTime dob = new DateTime(2002, 10, 22);  
  2. Console.WriteLine("ToString: " + dob.ToString());  
  3. Console.WriteLine("ToBinary: " + dob.ToBinary());  
  4. Console.WriteLine("ToFileTime: " + dob.ToFileTime());  
  5. Console.WriteLine("ToLocalTime: " + dob.ToLocalTime());  
  6. Console.WriteLine("ToLongDateString: " + dob.ToLongDateString());  
  7. Console.WriteLine("ToLongTimeString: " + dob.ToLongTimeString());  
  8. Console.WriteLine("ToOADate: " + dob.ToOADate());  
  9. Console.WriteLine("ToShortDateString: " + dob.ToShortDateString());  
  10. Console.WriteLine("ToShortTimeString: " + dob.ToShortTimeString());  
  11. Console.WriteLine("ToUniversalTime: " + dob.ToUniversalTime());  

 Listing 16

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

 

DateTimeImg5.gif
Figure 5

 

Summary

 

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

Up Next
    Ebook Download
    View all
    Learn
    View all