简体   繁体   中英

2 digit number in c#

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 eg00: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.

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.

When you "join them again", use .ToString("00") on each integer to get two digits. Alternatively, look into using a TimeSpan here.

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

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)

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM