2

I made timer, which outputs time like this:

0:1, 0:2, 0:3 ... 0:10 ...
string.Format("{0}:{1}", hours, minutes);

But I want to output as follows:

00:01, 00:02, 00:03

8 Answers 8

3
0:1, 0:2, 0:3 ... 0:10 ...
string.Format("{0:00}:{1:00}", hours, minutes);

Will output

00:01, 00:02, 00:03
Sign up to request clarification or add additional context in comments.

Comments

2

How about reading the .NET documentation at http://msdn.microsoft.com/en-us/library/system.string.format.aspx ? Many working samples already provided by others...

Comments

0

If you have a DateTime object, you can say:

DateTime dt = DateTime.Now;
// string.Format("{0:hh:mm}", dt);

If you have numbers, use:

string.Format("{0:00}:{1:00}", hours, minutes);

Comments

0
string.Format("{0,2}:{1,2}", hours, minutes);

Comments

0

In C# to have leading Zero you can use Format :

intValue.ToString("00.##");

So, if you want to have your minute and second with leading zero you can use:

string.Format("{0}:{1}", hours.ToString("00.##"), minutes.ToString("00.##"));

If your timer use the TimeSpan object you can use the Format for the TimeSpan:

myTimeSpan.Format("hh:mm");

Comments

0

you should take a look at this site. it gives a nice run-down on string formatting.

Comments

0

You could use the toString on the Timespan or datetime object or you could change you code to the following

string.Format("{0:00}:{1:00}");

Comments

0

i don't know if there is a simple and correct way of doing it.. but anyway you can write this

  String.Format("{0}:{1}",hours < 10 ? ("0" + hours) : hours,  minutes < 10 ? ("0" + minutes) : minutes);

hopes it's help... :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.