Reputation: 25
I have a program with a Timer
using the StopWatch
class.
There is a Label
that shows Hours, Minutes and seconds like this:
label.Text = String.Format("{0:00}:{1:00}:{2:00}", stopwatch.Elapsed.Hours, stopwatch.Elapsed.Minutes, stopwatch.Elapsed.Seconds);
Upvotes: 1
Views: 846
Reputation: 9649
This will get the elapsed seconds into the label:
label.Text = $"{stopwatch.ElapsedMilliseconds / 1000}";
Or this:
label.Text = $"{(int)stopwatch.Elapsed.TotalSeconds}";
Upvotes: 1
Reputation: 143363
Stopwatch.Elapsed
is property of struct TimeSpan
, which has bunch of properties with names starting with Total
, for example:
TimeSpan.FromMinutes(121).TotalHours // 2.0166666666666666
TimeSpan.FromSeconds(67).TotalSeconds // 67
Upvotes: 1
Reputation: 1346
You may want to use the TotalSeconds
property:
double totalSeconds = stopwatch.Elapsed.TotalSeconds;
To assign this value to your Label
s Text
property, do the following:
label.Text = totalSeconds.ToString();
Consider a cast
to int
or round the value, if you want to display full seconds only.
Upvotes: 4