简体   繁体   中英

String formatting

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

您可以在Timespan或datetime对象上使用toString,也可以将代码更改为以下内容

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

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