Mohanapriya R Mohanapriya R
Updated date May 02, 2024
In this article, we will learn how to convert strings into TimeSpan objects in C# with practical examples.

Parsing Strings to TimeSpan:

To convert strings into TimeSpan objects, we can use the TimeSpan.Parse or TimeSpan.TryParse methods provided by the TimeSpan structure. The Parse method is suitable when you expect the string to always represent a valid time duration, while TryParse is more forgiving and avoids throwing exceptions for invalid inputs.

using System;

class Program
{
    static void Main()
    {
        // Example strings representing time durations
        string durationString1 = "3.5:12:30";
        string durationString2 = "1:45:30";

        // Parsing strings to TimeSpan using TimeSpan.Parse
        TimeSpan timeSpan1 = TimeSpan.Parse(durationString1);
        TimeSpan timeSpan2;

        // Parsing strings to TimeSpan using TimeSpan.TryParse
        if (TimeSpan.TryParse(durationString2, out timeSpan2))
        {
            // Output the parsed TimeSpan values
            Console.WriteLine($"TimeSpan 1: {timeSpan1}");
            Console.WriteLine($"TimeSpan 2: {timeSpan2}");

            // Performing arithmetic operations with TimeSpans
            TimeSpan totalDuration = timeSpan1 + timeSpan2;
            Console.WriteLine($"Total Duration: {totalDuration}");
        }
        else
        {
            Console.WriteLine("Invalid time duration format for TimeSpan 2.");
        }
    }
}

Output:

TimeSpan 1: 3.12:30:00
TimeSpan 2: 1:45:30
Total Duration: 5.04:15:30

In this example, we have two strings representing time durations. We use both TimeSpan.Parse and TimeSpan.TryParse to convert them into TimeSpan objects, perform arithmetic operations and output the results.

Comments (0)

There are no comments. Be the first to comment!!!