Member-only story
TimeSpan in C# With Examples
The TimeSpan in C# is used to represent a duration or a time interval. TimeSpan in C# provides a convenient way to work with time-related values, such as differences between two dates and times. TimeSpan in C# is part of the System namespace and offers various properties and methods for performing calculations involving time intervals.
Features with timepsan in C#:
Creating a TimeSpan in C#:
You can create a TimeSpan in C# in several ways, including using constructors and parsing from a string
Example
using System;
// Using a constructor to create a TimeSpan
TimeSpan timeSpan1 = new TimeSpan(3, 2, 30, 15); // 3 days, 2 hours, 30 minutes, 15 seconds
// Parsing a TimeSpan from a string
TimeSpan timeSpan2 = TimeSpan.Parse("5.12:45:30.500"); // 5 days, 12 hours, 45 minutes, 30.5 seconds
Accessing TimeSpan Components in C#:
You can access various components of a TimeSpan in C#, such as days, hours, minutes, seconds, and milliseconds, using its properties:
int days = timeSpan1.Days; // 3
int hours = timeSpan1.Hours; // 2
int minutes = timeSpan1.Minutes; // 30
int seconds = timeSpan1.Seconds; // 15
int milliseconds = timeSpan1.Milliseconds; // 0