Share via


What is the difference between DateTime and TimeSpan class

Question

Tuesday, September 22, 2015 3:38 AM

datetime type variable could hold data about date and time but timespan could hold only time related data other than this what other major difference lies between these two class called DateTime and TimeSpan ?

thanks

All replies (2)

Tuesday, September 22, 2015 3:50 AM ✅Answered

Hi,

TimeSpan is a duration, not a time. For example, if you subtract a DateTime from another, you get a TimeSpan. If you add a TimeSpan to a DateTime, you geta new DateTime.

If you want to set the time part of a DateTime with a TimeSpan, you can use the Date property to get the date part.

myDateTime = myDateTime.Date + myTimeSpan;

https://msdn.microsoft.com/en-us/library/bb384267(v=vs.110).aspx

Hope this will help you.

thanks


Tuesday, September 22, 2015 4:36 AM ✅Answered

Hi sudip_inn,

Please refer to https://msdn.microsoft.com/en-us/library/system.timespan.aspx .

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. For example:

                var dateFrom = DateTime.Now;
                var dateTo = DateTime.Now.AddMinutes(-5);
                var diff = dateTo.Subtract(dateFrom);
                var res = String.Format("{0}:{1}:{2}", diff.Hours, diff.Minutes, diff.Seconds);

The "diff" object is a TimeSpan Object  which gives other useful properties.

Best Regards,

Nan Yu