开发者

String formatting

开发者 https://www.devze.com 2023-03-24 16:51 出处:网络
I made timer, which outputs time like this: 0:1, 0:2, 0:3 ... 0:10 ... str开发者_Go百科ing.Format(\"{0}:{1}\", hours, minutes);

I made timer, which outputs time like this:

0:1, 0:2, 0:3 ... 0:10 ...
str开发者_Go百科ing.Format("{0}:{1}", hours, minutes);

But I want to output as follows:

00:01, 00:02, 00:03


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

Will output

00:01, 00:02, 00:03


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


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);


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


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");


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


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}");


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

0

精彩评论

暂无评论...
验证码 换一张
取 消