Member-only story

TimeSpan in C# With Examples

Shahzad Aslam
4 min readJan 29, 2024

--

Timespan in C#

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

Arithmetic Operations of TimeSpan in C#:

You can perform arithmetic operations with TimeSpan objects in C#, such as addition and subtraction:.

TimeSpan total = timeSpan1 + timeSpan2; // Add two TimeSpans
TimeSpan difference = timeSpan1 - timeSpan2; // Subtract two TimeSpans

Comparison in TimeSpan in C#:

You can compare TimeSpan objects in C# using comparison operators (e.g., <,>, <=, >=) to check which one is greater or smaller:

bool isGreaterThan = timeSpan1 > timeSpan2; // Compare two TimeSpans

TimeSpan ToString in C#

TimeSpan provides a ToString method and supports custom format specifiers to represent time intervals in different formats:

string formatted = timeSpan1.ToString(); // Default format
string

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

No responses yet

Write a response