thevan
thevan

Reputation: 10354

Calculate Time Difference in C#:

I have two string variables such as StartTime and EndTime. I need to Calculate the TotalTime by subtracting the EndTime with StartTime.

The Format of StartTime and EndTime is as like follows:

    StartTime = "08:00 AM";
    EndTime = "04:00 PM";

TotalTime in Hours and Mins Format. How to calculate this using C#?

Upvotes: 1

Views: 18984

Answers (4)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Convert them to DateTime and substract one from other to get TimeSpan.

DateTime StartTime = DateTime.Parse("08:00 AM");

DateTime EndTime  = DateTime.Parse("04:00 PM"); // It converts this to 1600.

TimeSpan ts = EndTime - StartTime;

When i run above code it is giving me

ts.Days              // 0
ts.Hours             // 8
ts.Milliseconds      // 0
ts.Minutes           // 0
ts.Seconds           // 0
ts.Ticks             // 288000000000
ts.TotalDays         // 0.3333333333333333331
ts.TotalHours        // 8.0
ts.TotalMilliseconds // 28800000.0
ts.TotalMinutes      // 480.0
ts.TotalSeconds      // 28800.0

to get what you want.

Upvotes: 8

Guffa
Guffa

Reputation: 700362

Use the ParseExact method to specify the exact format when you parse the strings to DateTime values, then subtract them to get a TimeSpan value:

string StartTime = "08:00 AM";
string EndTime = "04:00 PM";

DateTime start = DateTime.ParseExact(StartTime, "hh:mm tt", CultureInfo.InvariantCulture);
DateTime end = DateTime.ParseExact(EndTime, "hh:mm tt", CultureInfo.InvariantCulture);

TimeSpan diff = end - start;

Console.WriteLine(diff.TotalMinutes);

Output:

480

Upvotes: 3

bart s
bart s

Reputation: 5100

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

DateTime d1 = DateTime.Parse(StartTime);
DateTime d2 = DateTime.Parse(EndTime);
TimeSpan ts = dt.Subtract(dt2);

Something like the above. You might need ParseExact instead of Parse

For your sample times, ts.ToString() will return a string "08:00:00" giving hours, minutes and seconds difference

Upvotes: 6

Kishore Kumar
Kishore Kumar

Reputation: 12874

string StartTime, EndTime;
StartTime = "08:00 AM"; 
EndTime = "04:00 PM"; 
DateTime startTime = DateTime.Parse(StartTime); 
DateTime endTime = DateTime.Parse(EndTime); 
TimeSpan ts = endTime.Subtract(startTime);

Output : 08:00:00 The put is in Hrs:Min:Sec format.

thats What you needed. Right

Note: endTime should come first while subtracting.

Upvotes: 2

Related Questions