Reputation: 423
A need some help, I have a TextBlock that contains a string like this 00:00:00 And I want to create a timer that will count every second e.g.00:00:01 , 00:00:02 etc
So the stupid thing that I do is to take the value of the text box
string[] times = myTextbox.Text.Split(':');
int hours = Int32.Parse(times[0]);
int minutes = Int32.Parse(times[1]);
int seconds = Int32.Parse(times[2]);
Then I increase the right variable and finally I join them again and put them back in the textblock, BUT now my counter is like this: 0:0:1, 0:0:2, ...
I know the problem, its very logical but my question is how can I solve it :)
Thank you very much.
Upvotes: 3
Views: 7960
Reputation: 3584
TimeSpan span = DateTime.Now.Subtract(startTimeOfTimer);
int Totalsec = span.Seconds;
int seconds = Totalsec % 60;
int minutes = span.Minutes;
int hour = span.Hours;
string Elapsedtime = string.Format("{0:00}:{1:00}:{2:00}",hour, minutes, seconds); that will output hour:min:sec as 00:00:00(two digit number)
Upvotes: 2
Reputation: 623
Instead of splitting the text of the textbox i would use DateTime.Parse like this:
var time = DateTime.Parse(myTextBox.Text);
then add a second:
time = time.AddSeconds(1);
and then finally, putting it back out there:
myTextBox.Text = time.ToString("myPattern");
where myPattern is replaced with any of the patterns described here: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
Upvotes: 4
Reputation: 70379
The following takes the string from the TextBox
, adds 1 second and return a string of the result (including correct wrapping around minutes/hours):
myTextbox.Text = TimeSpan.FromSeconds ( TimeSpan.Parse ( myTextbox.Text ).TotalSeconds + 1 ).ToString ( "c" );
One remark - you need to add exception handling in case that TextBox
is editable and might contain wrong data...
For some references see:
Upvotes: 1
Reputation: 69270
string displayString = String.Format("{0:00}:{1:00}:{2:00}",
hours, minutes, seconds);
The part after the :
is a format description. 00
means always use at least two positions and show an empty position as 0.
Upvotes: 8
Reputation: 1063501
When you "join them again", use .ToString("00")
on each integer to get two digits. Alternatively, look into using a TimeSpan here.
Upvotes: 7