-3

I have two time strings in HH:MM:SS:mmm:uuu format. How to find the difference (time span) between them?

string t1="06:37:30:210:111";
string t2="06:38:32:310:222";

I want to find the difference (in terms of time) between t2 and t1 (t2-t1).

How to do this?

Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
Anoop
  • 53
  • 2
  • 3
  • 9

2 Answers2

2

Try this:

class Program
{
    static void Main(string[] args)
    {
        string t1 = "06:37:30:210:111";
        string t2 = "06:38:32:310:222";

        var tp1 = TimeSpan.ParseExact(
            t1.Remove(t1.LastIndexOf(":")),
            @"hh\:mm\:ss\:FFFFFF",
            CultureInfo.InvariantCulture);

        var tp2 = TimeSpan.ParseExact(
            t2.Remove(t2.LastIndexOf(":")),
            @"hh\:mm\:ss\:FFFFFF",
            CultureInfo.InvariantCulture);

        Console.WriteLine(tp2 - tp1);
    }
}
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
1

You should convert your strings to DateTime and use TimeSpan to calculate the difference

DateTime d1 = DateTime.Parse(t1);
DateTime d2 = DateTime.Parse(t2);
TimeSpan ts = d2.Subtract(d1);
Sayse
  • 42,633
  • 14
  • 77
  • 146
Miller
  • 1,096
  • 9
  • 22