Using TimeSpan | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Using TimeSpan

How should a proper way of creating TimeSpan object look like? When I try: TimeSpan timeSpan=new TimeSpan(); I get an error.Why?

7th Feb 2018, 2:56 PM
Patryk Orlik
Patryk Orlik - avatar
3 Answers
+ 2
It important to understand that TimeSpan is a time-conversion object. It does not measure time. Made some code to test you statment but that is ok. https://code.sololearn.com/cfFyqI6Sj1VK So you set a time to the object and can display it in different ways. If you are looking to measure time you should use stopwatch Stopwatch stopwatch = new Stopwatch(); https://www.dotnetperls.com/stopwatch For the use of Timespan these are the examples from the link that vukan posted. //The default constructor initialize timespan to zero TimeSpan interval = new TimeSpan(); Console.WriteLine(interval.Equals(TimeSpan.Zero)); // So this will Displays "True". //TimeSpan.Zero field is a public static field of timespan class To dislay time set a time in the constructor TimeSpan interval = new TimeSpan(2, 14, 18); Console.WriteLine(interval.ToString()); // Displays "02:14:18". //use timespan to calculate with time DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0); DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0); TimeSpan travelTime = arrival - departure; Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime); // The example displays the following output: // 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00 This is a link that has more examples about how to use the timespan object. https://www.dotnetperls.com/timespan
7th Feb 2018, 9:13 PM
sneeze
sneeze - avatar
+ 6
https://msdn.microsoft.com/en-us/library/system.timespan(v=vs.110).aspx
7th Feb 2018, 4:50 PM
Vukan
Vukan - avatar
0
?
7th Feb 2018, 4:54 PM
Patryk Orlik
Patryk Orlik - avatar