Mastering DateTime In C#

Here is a detailed tutorial on C# DateTime class and how to work with dates and times using C#.

Introduction

 
Dates and times data types are very important in software applications. C# DateTime class is used to represent and work with Date and time. In this detailed tutorial, we will learn the following:
  1. What is DateTime
  2. DateTime Constructor, Field, Methods and Properties
  3. Operators in DateTime
  4. DateTime Formatting
  5. Managing Nullable DateTime
  6. Parse to DateTime object from String
  7. Working with Calendars
  8. Working with TimeZone
  9. DateTime with different Culture
  10. Starting with DateTimeOffSet
  11. TimeSpan features
Note: The aim of this article is to provide the overall idea of DateTime object and how we can work with different cultures, timezones, formatting etc. This article provides so many features of DateTime object which are collected from various sources.
 

What is DateTime

 
DateTime is a structure of value Type like int, double etc. It is available in System namespace and present in mscorlib.dll assembly. It implements interfaces like IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable. 
  1. public struct DateTime : IComparable, IFormattable, IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>  
  2. {  
  3.      // Contains methods and properties  
  4. }  
DateTime helps developer to find out more information about Date and Time like Get month, day, year, week day. It also helps to find date difference, add number of days to a date, etc.
 

DateTime Constructor

 
It initializes a new instance of DateTime object. At the time of object creation we need to pass required parameters like year, month, day, etc. It contains around 11 overload methods. More details available here.
  1. // 2015 is year, 12 is month, 25 is day  
  2. DateTime date1 = new DateTime(2015, 12, 25);   
  3. Console.WriteLine(date1.ToString()); // 12/25/2015 12:00:00 AM    
  4.   
  5. // 2015 - year, 12 - month, 25 – day, 10 – hour, 30 – minute, 50 - second  
  6. DateTime date2 = new DateTime(2012, 12, 25, 10, 30, 50);   
  7. Console.WriteLine(date1.ToString());// 12/25/2015 10:30:00 AM }  

DateTime Fields

 
DateTime object contains two static read-only fields called as MaxValue and Minvalue.
 
MinValue – It provides smallest possible value of DateTime. 
  1. // Define an uninitialized date.  
  2. Console.Write(DateTime.MinValue); // 1/1/0001 12:00:00 AM  
MaxValue – It provides smallest possible value of DateTime. 
  1. // Define an uninitialized date.  
  2. Console.Write(DateTime.MaxValue); // 12/31/9999 11:59:59 PM  

DateTime Methods

 
DateTime contains a variety of methods which help to manipulate DateTime Object. It helps to add number of days, hour, minute, seconds to a date, date difference, parsing from string to datetime object, get universal time and many more. More on DateTime Methods, visit here
 
Here are a couple of DateTime Methods: 
  1. // Creating TimeSpan object of one month(as 30 days)  
  2. System.TimeSpan duration = new System.TimeSpan(30, 0, 0, 0);  
  3. System.DateTime newDate1 = DateTime.Now.Add(duration);  
  4. System.Console.WriteLine(newDate1); // 1/19/2016 11:47:52 AM  
  5.    
  6. // Adding days to a date  
  7. DateTime today = DateTime.Now; // 12/20/2015 11:48:09 AM  
  8. DateTime newDate2 = today.AddDays(30); // Adding one month(as 30 days)  
  9. Console.WriteLine(newDate2); // 1/19/2016 11:48:09 AM  
  10.   
  11. // Parsing  
  12. string dateString = "Wed Dec 30, 2015";  
  13. DateTime dateTime12 = DateTime.Parse(dateString); // 12/30/2015 12:00:00 AM  
  14.   
  15. // Date Difference  
  16. System.DateTime date1 = new System.DateTime(2015, 3, 10, 2, 15, 10);  
  17. System.DateTime date2 = new System.DateTime(2015, 7, 15, 6, 30, 20);  
  18. System.DateTime date3 = new System.DateTime(2015, 12, 28, 10, 45, 30);  
  19.   
  20. // diff1 gets 127 days, 04 hours, 15 minutes and 10 seconds.  
  21. System.TimeSpan diff1 = date2.Subtract(date1); // 127.04:15:10  
  22. // date4 gets 8/23/2015 6:30:20 AM  
  23. System.DateTime date4 = date3.Subtract(diff1);  
  24. // diff2 gets 166 days 4 hours, 15 minutes and 10 seconds.  
  25. System.TimeSpan diff2 = date3 - date2; //166.04:15:10  
  26. // date5 gets 3/10/2015 2:15:10 AM  
  27. System.DateTime date5 = date2 - diff1;  
  28.   
  29. // Universal Time  
  30. DateTime dateObj = new DateTime(2015, 12, 20, 10, 20, 30);  
  31. Console.WriteLine("mans" + dateObj.ToUniversalTime()); // 12/20/2015 4:50:30 AM  

DateTime Properties

 
It contains properties like Day, Month, Year, Hour, Minute, Second, DayOfWeek and others in a DateTime object.
  1. DateTime myDate = new DateTime(2015, 12, 25, 10, 30, 45);  
  2. int year = myDate.Year; // 2015  
  3. int month = myDate.Month; //12  
  4. int day = myDate.Day; // 25  
  5. int hour = myDate.Hour; // 10  
  6. int minute = myDate.Minute; // 30  
  7. int second = myDate.Second; // 45  
  8. int weekDay = (int)myDate.DayOfWeek; // 5 due to Friday  
DayOfWeek
 
It specifies day of the week like Sunday, Monday etc. It is an enum which starts from Sunday to Saturday. If you cast the weekofday value to integer then it starts from Zero (0) for Sunday to Six (6) for Saturday.
  1. DateTime dt = new DateTime(2015, 12, 25);  
  2. bool isEqual = dt.DayOfWeek == DayOfWeek.Thursday); // False  
  3. bool isEqual = dt.DayOfWeek == DayOfWeek.Friday); // True  
DateTimeKind
 
It specifies whether a DateTime object is Unspecified, Utc or Local time. It is enum type with values: Unspecified(0), Utc(1), Local(2).
  1. DateTime saveNow = DateTime.Now;  
  2. DateTime saveUtcNow = DateTime.UtcNow;  
  3.   
  4. DateTime myDate = DateTime.SpecifyKind(saveUtcNow, DateTimeKind.Utc); // 12/20/2015 12:17:18 PM  
  5. DateTime myDate2 = DateTime.SpecifyKind(saveNow, DateTimeKind.Local); // 12/20/2015 5:47:17 PM  
  6.   
  7. Console.WriteLine("Kind: " + myDate.Kind); // Utc  
  8. Console.WriteLine("Kind: " + myDate2.Kind); // Local  
More on DateTime properties visit here.
 

DateTime Operators

 
DateTime object facilitates to perform addition, subtraction, equality, greater than using operators like “+”, “-”, “==” etc. Here are couples of examples:
  1. // It is 10th December 2015  
  2. System.DateTime dtObject = new System.DateTime(2015, 12, 10); // 12/10/2015 12:00:00 AM  
  3. // TimeSpan object with 15 days, 10 hours, 5 minutes and 1 second.  
  4. System.TimeSpan timeSpan = new System.TimeSpan(15, 10, 5, 1);  
  5. System.DateTime addResult = dtObject + timeSpan; // 12/25/2015 10:05:01 AM  
  6. System.DateTime substarctResult = dtObject - timeSpan; // 11/24/2015 1:54:59 PM  

  7. DateTime dec25 = new DateTime(2015, 12, 25);  
  8. DateTime dec15 = new DateTime(2015, 12, 15);  

  9. // areEqual gets false.  
  10. bool areEqual = dec25 == dec15;  
  11. DateTime newDate = new DateTime(2015, 12, 25);  
  12. // areEqual gets true.  
  13. areEqual = dec25 == newDate  
More on operators, please visit here
 

DateTime Formatting

 
Different users need different kinds of  format date. For instance some users need date like "mm/dd/yyyy", some need "dd-mm-yyyy". Let's say current Date Time is "12/8/2015 3:15:19 PM" and as per specifier you will get below output.
  1. DateTime tempDate = new DateTime(2015, 12, 08); // creating date object with 8th December 2015  
  2. Console.WriteLine(tempDate.ToString("MMMM dd, yyyy")); //December 08, 2105.  
Below specifiers will help you to get the date in different formats.
 
Specifier Description Output
d Short Date 12/8/2015
D Long Date Tuesday, December 08, 2015
t Short Time 3:15 PM
T Long Time 3:15:19 PM
f Full date and time Tuesday, December 08, 2015 3:15 PM
F Full date and time (long) Tuesday, December 08, 2015 3:15:19 PM
g Default date and time 12/8/2015 15:15
G Default date and time (long) 12/8/2015 15:15
M Day / Month 8-Dec
r RFC1123 date Tue, 08 Dec 2015 15:15:19 GMT
s Sortable date/time 2015-12-08T15:15:19
u Universal time, local timezone 2015-12-08 15:15:19Z
Y Month / Year December, 2015
dd Day 8
ddd Short Day Name Tue
dddd Full Day Name Tuesday
hh 2 digit hour 3
HH 2 digit hour (24 hour) 15
mm 2 digit minute 15
MM Month 12
MMM Short Month name Dec
MMMM Month name December
ss seconds 19
fff milliseconds 120
FFF milliseconds without trailing zero 12
tt AM/PM PM
yy 2 digit year 15
yyyy 4 digit year 2015
: Hours, minutes, seconds separator, e.g. {0:hh:mm:ss} 9:08:59
/ Year, month , day separator, e.g. {0:dd/MM/yyyy} 8/4/2007
 

Handling Nullable DateTime

 
DateTime is a Value Type like int, double etc. so there is no way to assign a null value. When a type can be assigned null it is called nullable, that means the type has no value. All Reference Types are nullable by default, e.g. String, and all ValueTypes are not, e.g. Int32. The Nullable<T> structure is using a value type as a nullable type.
 
By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C#, you can achieve this using a question mark (?) after the type or using the generic style Nullable.
  1. Nullable <DateTime> nullDateTime;  
  2. DateTime? nullDateTime = null; 

Parse string to DateTime object

 
Sometimes we do parsing from string to DateTime object to perform operations like date difference, weekday, month name etc. For instance, there is a string value (“12/10/2015”) and our requirement is to find out weekday (Sunday or Monday and so on) of date. In this scenario we need to convert string value to DateTime object and then use WeekDay property(obj.WeekDay) to find out weekday. We can accomplish the same by built-in methods like Convert.ToDateTime(), DateTime.Parse(), DateTime.ParseExact(), DateTime.TryParse(), DateTime.TryParseExact(). Here are a few examples of how to parse a string to DateTime object:
  1. CultureInfo culture = new CultureInfo("en-US");  
  2.   
  3. DateTime dateTimeObj = Convert.ToDateTime("10/22/2015 12:10:15 PM", culture);  
  4. DateTime dateTimeObj = DateTime.Parse("10/22/2015 12:10:15 PM");  
  5. DateTime dateTimeObj = DateTime.ParseExact("10-22-2015""MM-dd-yyyy", provider); // 10/22/2015 12:00:00 AM  
  6.   
  7. DateTime dateTimeObj; // 10-22-2015 12:00:00 AM  
  8. bool isSuccess = DateTime.TryParse("10-22-2015"out dateTimeObj); // True  
  9.   
  10. DateTime dateTimeObj; // 10/22/2015 12:00:00 AM  
  11. CultureInfo provider = CultureInfo.InvariantCulture;  
  12. bool isSuccess = DateTime.TryParseExact("10-22-2015""MM-dd-yyyy", provider, DateTimeStyles.None, out dateTimeObj); // True  
Now a question arises in your mind, that is, why do we have so many methods for parsing? The reason is every method is for a different purpose. Use TryParse() when you want to be able to attempt a parse and handle invalid data immediately (instead of throwing the exception), and ParseExact() when the format you are expecting is not a standard format, or when you want to limit to one particular standard format for efficiency. If you're sure the string is a valid DateTime, and you know the format, you could also consider the DateTime.ParseExact() or DateTime.TryParseExact() methods.
 
More on this visit here.
 

Working with Calendars

  
Although DateTime object stores Date and Time information but it also depends on Calendar. Calendar class is an abstract class which is present in System.Globalization namespace. There are different types of Calendar available in .Net framework. These are ChineseLunisolarCalendar, GregorianCalendar, HebrewCalendar, HijriCalendar, JapaneseCalendar, JapaneseLunisolarCalendar, JulianCalendar, KoreanCalendar, KoreanLunisolarCalendar, PersianCalendar, TaiwanCalendar, TaiwanLunisolarCalendar, ThaiBuddhistCalendar, UmAlQuraCalendar.
 
Calendar can be used in two ways:
  • Using CultureInfo object
  • Using Calendar object. It is for Calendars that are independent of culture: ChineseLunisolarCalendar, JapaneseLunisolarCalendar, JulianCalendar, KoreanLunisolarCalendar,PersianCalendar and TaiwanLunisolarCalendar. 
You can know your current Calendar information using following code:
  1. CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;  
  2. Calendar cl = currentCulture.Calendar; // System.Globalization.GregorianCalendar  
  3. string temip = cl.ToString().Replace("System.Globalization.""");  
  4.   
  5. // 4th Jan 2016 - current date  
  6. Calendar calendar = new HijriCalendar();  
  7. DateTime dt10 = new DateTime(2016, 01, 04, calendar);// Uses month 13!  
  8. Console.WriteLine("HijriCalendar year: " + dt10.Year); // 2141  
  9. Console.WriteLine("HijriCalendar month: " + dt10.Month); // 9  
  10. Console.WriteLine("HijriCalendar total date: " + dt10.ToString("d")); // 9  
  11.   
  12. // Converting one Calendar value to another - Option1  
  13. var calendar1 = new HijriCalendar();  
  14. var hijriYear = calendar1.GetYear(DateTime.Now); // 1437  
  15. var hijriMonth = calendar1.GetMonth(DateTime.Now); // 3  
  16. var hijriDay = calendar1.GetDayOfMonth(DateTime.Now); // 24  
  17.   
  18. //- Option2  
  19. DateTime utc = DateTime.Now;  
  20. var ci = CultureInfo.CreateSpecificCulture("ar-SA");  
  21. string s = utc.ToString(ci); // 24/03/37 08:15:03 ?  
  22. A calendar divides into multiple eras. In .Net framework it supports only one era except JapaneseCalendar (supports multiple).  

  23. Calendar cal = new JapaneseCalendar();  
  24. foreach (int era in cal.Eras) {  
  25. DateTime date2 = cal.ToDateTime(year, month, day, 0, 0, 0, 0, era);  
  26.   
  27. Console.WriteLine("{0}/{1}/{2} era {3} in Japanese Calendar -> {4:d} in Gregorian",  
  28. cal.GetMonth(date2), cal.GetDayOfMonth(date2),  
  29. cal.GetYear(date2), cal.GetEra(date2), date2);

Working with TimeZone object

 
TimeZoneInfo class represents world time like Indian Standard Time (IST), US Eastern Standard Time, Tokyo Standard Time etc. It is present in System namespace. It recognizes Local Time Zone and converts times between Coordinated Universal Time (UTC) and local time. It helps to get time in Time Zone (Indis or Japan or USA), converts time between two Time Zone(Australia time zone to India Standard time) and serializes a Date Time.
 
It is a sealed class and you can’t create an instance of this class. You need to call static members and methods. Static methods like CreateCustomTimeZone(), FindSystemTimeZoneById(), FromSerializedString(), GetSystemTimeZonesand properties like Utc and Local. Here area couple examples:
  1. //If you want to convert it back from UTC:  
  2. DateTime now = DateTime.UtcNow;  
  3. DateTime tempD = TimeZone.CurrentTimeZone.ToLocalTime(now);  
  4. // Get current TimeZone  
  5. string current = TimeZone.CurrentTimeZone.StandardName;  
  6.   
  7. // Get All Time Zones  
  8. foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())  
  9. {  
  10.     Console.WriteLine(z.Id);  
  11. }  
  12.   
  13. //If you want to convert any date from your time-zone to UTC do this:  
  14. DateTime tempD1 = TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now);  
  15.   
  16. // Get Tokyo Standard Time zone from Local time Zone(India)  
  17. TimeZoneInfo tzObject = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");  
  18. DateTime tstTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, tzObject);  
  19. Console.WriteLine("1. Time in {0} zone: {1}", tzObject.IsDaylightSavingTime(tstTime) ?  
  20. tzObject.DaylightName : tzObject.StandardName, tstTime);  
  21.   
  22. // Converting Austrlia Standard Time to Indian Standrd Time  
  23. TimeZoneInfo tzObject1 = TimeZoneInfo.FindSystemTimeZoneById("AUS Central Standard Time");  
  24. DateTime tstTime2 = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, tzObject1);  
  25. Console.WriteLine("2. Time in {0} zone: {1}", tzObject1.IsDaylightSavingTime(tstTime2) ?  
  26. tzObject1.DaylightName : tzObject1.StandardName, tstTime2);  
  27.   
  28. // Converting value to UTC time zone to make comfortale with TimeZone  
  29. DateTime ut1 = TimeZoneInfo.ConvertTimeToUtc(tstTime2, tzObject1);  
  30.   
  31. TimeZoneInfo tzObject2 = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");  
  32. DateTime tstTime3 = TimeZoneInfo.ConvertTime(ut1, TimeZoneInfo.Utc, tzObject2);  
  33. Console.WriteLine("3. Time in {0} zone: {1}", tzObject2.IsDaylightSavingTime(tstTime3) ?  
  34. tzObject2.DaylightName : tzObject2.StandardName, tstTime3);  

DateTime with Different Culture

 
.Net uses CultureInfo class for providing information about specific culture. The information is writing system, date, number, string, and calendar. It is present in System.Globalization namespace.
  1. // Current culture name  
  2. string currentCulture = Thread.CurrentThread.CurrentCulture.DisplayName;  
  3.   
  4. DateTime currentTime = DateTime.Now; //"1/9/2016 10:22:45 AM"  
  5. //// Getting DateTime based on culture.  
  6. string dateInUSA = currentTime.ToString("D"new CultureInfo("en-US")); // USA - Saturday, January 09, 2016  
  7. string dateInHindi = currentTime.ToString("D"new CultureInfo("hi-IN")); // Hindi - 09 ????? 2016  
  8. string dateInJapan = currentTime.ToString("D"new CultureInfo("ja-JP")); // Japan - 2016?1?9?  
  9. string dateInFrench = currentTime.ToString("D"new CultureInfo("fr-FR")); // French - samedi 9 janvier 2016  
  10.   
  11. string dateInOriya = currentTime.ToString("D"new CultureInfo("or")); // Oriya - 09 ???????? 2016  
  12. // Convert Hindi Date to French Date  
  13. DateTime originalResult = new DateTime(2016, 01, 09);  
  14. // Converting Hindi Date to DateTime object  
  15. bool success = DateTime.TryParse(dateInHindi, new System.Globalization.CultureInfo("hi-IN"),  
  16. System.Globalization.DateTimeStyles.None, out originalResult);  
  17.   
  18. // Next convert current date to French date  
  19. string frenchTDate = originalResult.ToString("D"new CultureInfo("fr-FR")); // French - samedi 9 janvier 2016  
  20.   
  21. // To get DatePattern from Culture  
  22. CultureInfo fr = new CultureInfo("fr-FR");  
  23. string shortUsDateFormatString = fr.DateTimeFormat.LongDatePattern;  
  24. string shortUsTimeFormatString = fr.DateTimeFormat.ShortTimePattern;  
  25.   
  26. // To get all installed culture in .Net version  
  27. foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes. AllCultures))  
  28. {  
  29.     Console.WriteLine(ci.Name + ", " + ci.EnglishName);  
  30. }  
  31.    

What is DateTimeOffset?

 
It is a structure type like DateTime. It is introduced in .Net framework 3.5 and present in System namespace. It is mostly relative to Universal Coordinated Time (UTC).
 
DateTimeOffset is Date + Time + Offset. It provides precise information because it contains offset from Date and Time is taken. DateTimeOffset provides same properties as DateTime structure like Day, Month, Year, Hour, Minute, Second etc. However DateTimeOffset has some new properties:
  • DateTime
    Gets the DateTime portion of the value without regard to the offset.

  • LocalDateTime
    Returns a DateTime representing the value in respect to the local time zone.

  • Offset
    Returns the time offset from UTC.

  • UtcDateTime
    Returns a DateTime representing the value in respect to UTC time. 
Follow example, we declare date variable of DateTimeOffset type and assign current DateTime to it. You will get a result like: 1/9/2016 2:27:00 PM +05:30. Here “1/9/2016 2:27:00 PM” is datetime and “+05:30” (5 hours 30 minutes) is your Offset value. Means if you add offset value to date time (1/9/2016 2:27:00 PM) you will get UTC time. It provides a better way to work with different times from different time zones.
  1. // Original time: 1/9/2016 2:27:00 PM  
  2. DateTimeOffset date = DateTimeOffset.Now; // 1/9/2016 2:27:00 PM +05:30  
  3.   
  4. // You can get Offset value using Offset property  
  5. DateTimeOffset dateTimeObj = DateTime.Now;  
  6. dateTimeObj.Offset.Hours // 5  
  7. dateTimeObj.Offset.Minutes //30  
  8. dateTimeObj.Offset.Seconds // 0  
  9.   
  10. // Get only DateTime from DateTimeOffset  
  11. dateTimeObj.DateTime // 1/9/2016 2:27:00 PM  
  12.   
  13. // Get Utc time from DateTime Offset  
  14. dateTimeObj.UtcDateTime.ToString() // 1/9/2016 7:57:00 PM  
  15.   
  16. // Get Utc from local time  
  17. DateTime utcTimeObj = DateTimeOffset.Parse(DateTime.Now.ToString()).UtcDateTime;  
  18.   
  19. // Another way to get Utc from local time  
  20. DateTime utcTimeObj = DateTime.Now.ToUniversalTime();  
  21.   
  22. // Get local time from Utc time  
  23. DateTime localVersion = DateTime.UtcNow.ToLocalTime();  
  24.   
  25. // Another way to get local(India) time from Utc time  
  26. localVersion = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));  
DateTime is a more powerful structure for manipulating datetime but it is less portable when working with times from different time zones. The DateTimeOffset is much more portable in that it preserves the offset from UTC. So choose as per your requirement.
 

Working with TimeSpan

 
It is a structure type which is present in System namespace. It represents time interval and can be expressed as days, hours, minutes, and seconds. It helps to fetch days, hour, minutes and seconds between two dates.
 
You can create instance of TimeSpan object. It contains 4 parameterized constructors which take days, hours, minutes, seconds, and milliseconds as parameter. Here is the example:
  1. TimeSpan ts = new TimeSpan(10, 40, 20); // 10 - hour, 40 - minute, 20 - second  
  2. TimeSpan ts1 = new TimeSpan(1, 2, 5, 10); // 1 - day, 2 - hour, 5 - minute, 10 – seconds  
  3.   
  4. // You can add TimeSpan with DateTime object as well as TimeSpan object.  
  5. TimeSpan ts = new TimeSpan(10, 40, 20); // 10 - hour, 40 - minute, 20 - second  
  6. TimeSpan ts1 = new TimeSpan(1, 2, 5, 10); // 1 - day, 2 - hour, 5 - minute, 10 – seconds  
  7.   
  8. DateTime tt = DateTime.Now + ts; // Addition with DateTime  
  9. ts.Add(ts1); // Addition with TimeSpan Object  
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond, or 10 million ticks in a second.
  1. TimeSpan ts3 = new TimeSpan(10000000);  
  2. double secondFromTs = ts3.TotalSeconds; // 1 second  
  3. Console.WriteLine(secondFromTs);  
Below is the example of how to get the exact date difference between them using TimeSpan: 
  1. // Define two dates.  
  2. DateTime date1 = new DateTime(2016, 1, 10, 11, 20, 30);  
  3. DateTime date2 = new DateTime(2016, 2, 20, 12, 25, 35);  
  4.   
  5. // Calculate the interval between the two dates.  
  6. TimeSpan interval = date2 - date1;  
  7.   
  8. // Display individual properties of the resulting TimeSpan object.  
  9. Console.WriteLine("No of Days:", interval.Days); // 41  
  10. Console.WriteLine("Total No of Days:", interval.TotalDays); // 41.0451  
  11. Console.WriteLine("No of Hours:", interval.Hours); //1  
  12. Console.WriteLine("Total No of Hours:", interval.TotalHours); // 985.084  
  13. Console.WriteLine("No of Minutes:", interval.Minutes); // 5  
  14. Console.WriteLine("Total No of Minutes:", interval.TotalMinutes); // 59105.833  
  15. Console.WriteLine("No of Seconds:", interval.Seconds); // 5  
  16. Console.WriteLine("Total No of Seconds:", interval.TotalSeconds); // 3546305.0  
  17. Console.WriteLine("No of Milliseconds:", interval.Milliseconds); // 0  
  18. Console.WriteLine("Total No of Milliseconds:", interval.TotalMilliseconds); // 3546305000  
  19. Console.WriteLine("Ticks:", interval.Ticks); // 354630500000000  
Here you will get one doubt as to the difference between Hours and TotalHours. Hours property represents difference between two dates hours value (12-11). However TotalHours represents total number of hours difference between two dates. First it calculates days between two and then multiplies 24 hours into it.
 

Conclusion 

 
In this article we discussed about DateTime object in C#. It also contains how to work with different cultures, timezones, formmatting, date differences and others. Hope it will help you often.
 
References
 
https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx