Netanelgo
Netanelgo

Reputation: 49

How can I subtract datetimes to give the results in the format I require?

I'm trying to subtract between two dateTimes in a way that I'll see all totaled hours.(including mm and ss if theres any) for Example:

TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("04/05/2015 14:00:00")); 

I want to return a string that contains "46:00:00"

TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("05/05/2015 12:00:00")); 

I want to return a string that contains "24:00:00"

TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("05/05/2015 18:00:00")); 

I want to return a string that contains "18:00:00"

Upvotes: 1

Views: 183

Answers (3)

man_luck
man_luck

Reputation: 1656

i have done something like:

TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("04/05/2015 14:00:00"));
int i = 0;
if(j.Days >= 1)
{
    i = j.Days * 24;
    i = i + j.Hours;
}
string s = String.Concat(i.ToString(), ":", j.Minutes.ToString(), ":", j.Seconds.ToString());

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use TimeSpan.TotalHours and String.Format:

string result = string.Format("{0:D2}:{1:D2}:{2:D2}", (int)j.TotalHours, j.Minutes, j.Seconds);

The cast to int is needed to remove the fractional part from the TotalHours.

The D2 ensures that you always get two digits like 00 even if the minute part is 0.

MSDN: The "D" (or decimal) format specifier

Upvotes: 4

gkrishy
gkrishy

Reputation: 756

Try Something like this,

I have done only for your first condition

 DateTime d1 = Convert.ToDateTime( "06/05/2015 12:00:00");
 DateTime d2 = Convert.ToDateTime( "04/05/2015 14:00:00");
 TimeSpan j = d1 - d2;
 string ti = (j.TotalHours + " : " + j.TotalMinutes + " : " + j.TotalSeconds).ToString();

Upvotes: 0

Related Questions