Wednesday, March 28, 2012

Subtracting 2 Times

Hi AllI'm trying to subtract 2 times.

T1 = 3:50:00 PM

T2 = 4:00:00 PM

T3 = T2.Subtract(T1)


But I'm getting the errorCannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'.

Please give me a solution


what type of variable is T3 defined as? T3 needs to be a TimeSpan not a date time. The subtraction of two times is a time span not a time itself. as in 1:24 - 1:12 = 12 minutes. 12 minutes is not a time it is a time span.

I hope that helps,
Brendan


Hi

By using Timespan I'm having the following codes. But i'm gettingerror message in t1, t2, t3

DateTime dt1, dt2, dt3;
dt1 = System.DateTime.Now;
dt2 = System.DateTime.Now;

TimeSpan t1, t2, t3;

t1 = System.Convert.ToDateTime(dt1).ToLongTimeString();
t2 = System.Convert.ToDateTime(dt2).ToLongTimeString();
t3 = t2.Subtract(t1);
Label3.Text = t3;

Please rectify this.


Hi

The following code must work

T1 = 3:50:00 PM

T2 = 4:00:00 PM

TimeSpan tsp = T2.Subtract(T1);

Label3.Text = tsp.TotalHours.ToString() + ":" + tsp.TotalMinutes.ToString() + ":" + tsp.TotalSeconds.ToString()


Hi as you'll notice from my first post. I mentioned that t3 was likely a datetime, and it needs to be a timespan. The other 2 should be datetimes, so t1 and t2 are DateTimes. Then you make t3 a timespan.

DateTime t1, t2;TimeSpan t3;t3 = t2.Subtract(t1);Label3.Text = t3.ToString();

I hope that helps,
Brendan

0 comments:

Post a Comment